Skip to main content

prefer-single-widget-per-file

added in: 1.6.0
⚙️
Pro+
preset: recommended

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).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-single-widget-per-file:
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
dart_code_metrics:
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) {
...
}
}