Skip to main content

prefer-static-class

added in: 1.6.0
⚙️
Pro+

Suggests declaring static class members instead of global constants, variables and functions.

Static class members help introduce a naming scope for their static members which in turn helps reduce naming conflicts and improves IDE autocomplete. Additionally, the member-ordering rule works only for member declarations.

info

When fixing rule issues and moving global members into a class, consider also renaming them to avoid duplicating context. For example, getCircleArea global function should become Circle.getArea, not Circle.getCircleArea.

note

For this rule it's recommended to exclude the test folder.

⚙️ Config

Set ignore-private (default is false) to ignore private global declarations.

Set ignore-names (default is empty) to ignore names matching regular expressions (for example, Riverpod providers, Flutter hooks, etc).

Set ignore-annotations (default is [FunctionalWidget, swidget, hwidget, hcwidget, riverpod]) to override default ignored annotation list.

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-static-class:
ignore-private: false
ignore-annotations:
- allowedAnnotation
ignore-names:
- (.*)Provider
- use(.*)

Example

❌ Bad:

int getCircleArea() {} // LINT: Prefer declaring static class members instead of global functions, variables and constants.
int getPerimeter() // LINT: Prefer declaring static class members instead of global functions, variables and constants.

// LINT: Prefer declaring static class members instead of global functions, variables and constants.
const _PI = 3.14;

✅ Good:

class Circle {
static int getArea() {}
static int getPerimeter() {}

static const _PI = 3.14;
}