Skip to main content

prefer-static-class

added in: 1.0.0 style

Suggests to use static class member instead of global constants, variables and functions.

Pros:

  • Easy to search: great help from IDE autocomplete. Type class/file name to find domain, and type dot to list all members.
  • Easy to import: name conflicts will happen less often since all names are scoped to file name/class name. No need to use import 'file.dart' as 'file' to resolve name conflicts.
  • Easy to read: declarations in code will be always shown paired with domain they belong to. Compare Circle.getArea and getArea or getCircleArea.
  • member-ordering rule will be applied to class members.

Cons:

  • The code amount slightly increases.
info

When fixing rule issues and moving global members into a class, consider also renaming 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 none) 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.

dart_code_linter:
...
rules:
...
- prefer-static-class
ignore-annotations:
- allowedAnnotation
ignore-private: true
ignore-names:
- (.*)Provider
- use(.*)

Example

Bad:

// circle.dart
int getCircleArea() {} // LINT
int getPerimeter() // LINT

const _PI = 3.14; // LINT

Good:

// circle.dart
class Circle {
static int getArea() {}
static int getPerimeter() {}

static const _PI = 3.14;
}