Skip to main content

prefer-single-declaration-per-file

added in: 1.17.0
⚙️
Pro+

Warns when a file contains more than one top-level declaration (class, mixin, extension, enum or extension type).

note

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

⚙️ Config

Set ignore-private (default is true) to ignore private declarations (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-single-declaration-per-file:
ignore-private: true

Example

❌ Bad:

some_class.dart

class SomeClass {}

// LINT: Prefer only one top-level declaration per file. Try moving this declaration to a separate file or making it private.
class SomeOtherClass {}

class _Another {} // Correct, ignored by default

✅ Good:

some_class.dart

class SomeClass {}

some_other_class.dart

class SomeOtherClass {}

Example with "ignore-private"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-single-declaration-per-file:
ignore-private: false

❌ Bad:

some_class.dart

class SomeClass {}

// LINT: Prefer only one top-level declaration per file. Try moving this declaration to a separate file or making it private.
class _Another {} // Correct, ignored by default