Skip to content

prefer_single_widget_per_file

v0.4.0WarningConfigurableWidget Best Practices

This rule warns when a file contains more than one public widget class. The first public widget is fine, but the second and any subsequent ones trigger the lint. Private widgets (prefixed with _) and non-widget classes are not counted.

Having multiple public widgets in one file makes them harder to find, harder to test independently, and harder to reason about in code reviews. A one-widget-per-file convention keeps files focused, makes the file system a natural index of your widget library, and ensures that imports pull in exactly what is needed.

See also: Flutter performance best practices

// Two public widgets in the same file
class FirstWidget extends StatelessWidget {
@override
Widget build(BuildContext context) => const Text('First');
}
// This triggers the lint
class SecondWidget extends StatelessWidget {
@override
Widget build(BuildContext context) => const Text('Second');
}
// first_widget.dart — one public widget per file
class FirstWidget extends StatelessWidget {
@override
Widget build(BuildContext context) => const Text('First');
}
// Private helpers are fine in the same file
class _HelperWidget extends StatelessWidget {
const _HelperWidget();
@override
Widget build(BuildContext context) => const Text('Helper');
}

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_single_widget_per_file: true

To turn it off again:

many_lints.yaml
rules:
prefer_single_widget_per_file: false

To keep the rule on but skip certain paths, use per-rule exclude.

analysis_options.yaml
many_lints:
rules:
prefer_single_widget_per_file:
ignore_private_widgets: false
ignore_visible_for_testing: true
Option Type Default Description
ignore_private_widgets bool true Skip widgets whose name starts with _
ignore_visible_for_testing bool false Skip widgets annotated @visibleForTesting