Skip to main content

prefer-single-widget-per-file

effort: 5m
configurable
free+

Warns when a file contains more than one widget.

Ensures that files have single responsibility and each complex widget exists in its own file.

note

You can fix this rule's issues using the 'Move to File' assist.

⚙️ Config

Set ignore-private-widgets (default is false) to ignore private widgets (example).

Set ignore-visible-for-testing (default is false) to ignore widgets annotated with @visibleForTesting.

analysis_options.yaml
dcm:
rules:
- prefer-single-widget-per-file:
ignore-visible-for-testing: false
ignore-private-widgets: false

Example

❌ Bad:

some_widget.dart
class SomeWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

// LINT: Prefer only one widget per file. Try moving the widget to a separate file.
class SomeOtherWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

// LINT: Prefer only one widget per file. Try moving the widget to a separate file.
class _SomeOtherWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

// LINT: Prefer only one widget per file. Try moving the widget to a separate file.
class SomeStatefulWidget extends StatefulWidget {

_SomeStatefulWidgetState createState() => _someStatefulWidgetState();
}

class _SomeStatefulWidgetState extends State<InspirationCard> {

Widget build(BuildContext context) {
...
}
}

✅ Good:

some_widget.dart
class SomeWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}
some_other_widget.dart
class SomeOtherWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

Example with "ignore-private-widgets"

Config
analysis_options.yaml
dcm:
rules:
- prefer-single-widget-per-file:
ignore-private-widgets: true

✅ Good:

some_widget.dart
class SomeWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

// Correct, private widgets are ignored
class _SomeOtherWidget extends StatelessWidget {

Widget build(BuildContext context) {
...
}
}

Rules of the Week