Skip to main content

prefer-declaring-const-constructor

added in: 1.0.0
⚙️🛠
Pro+
preset: recommended

Warns when a class with no non-final fields has a non-constant constructor declaration.

Declaring const class constructors allows creating const instances and it's usually preferable to declare const constructors everywhere possible.

⚙️ Config

Set allow-one (default is false) to allow at least one const constructor (example).

Set ignore-abstract (default is true) to highlight abstract and sealed classes (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-declaring-const-constructor:
allow-one: false
ignore-abstract: true

Example

❌ Bad:

// LINT: Prefer declaring a const constructor.
class MyException implements Exception {}

class Square {
Square(this.sideLength); // LINT: Prefer declaring a const constructor.

// LINT: Prefer declaring a const constructor.
Square.fromRadius(double radius) : sideLength = 2 * radius;

final double sideLength;
}

class Square {
// LINT: Prefer declaring a const constructor.
Square(this.sideLength, this.color);

final double sideLength;
final Color color;
}

✅ Good:

class MyException implements Exception {
const MyException();
}

class Square {
const Square(this.sideLength);

const Square.fromRadius(double radius) : sideLength = 2 * radius;

final double sideLength;
}

class Square {
const Square(this.sideLength, this.color);

final double sideLength;
final Color color;
}

Example with "allow-one"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-declaring-const-constructor:
allow-one: true

✅ Good:

class Square {
const Square(this.sideLength);

// Correct, already has one const constructor
Square.fromRadius(double radius) : sideLength = 2 * radius;

final double sideLength;
}

Example with "ignore-abstract"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-declaring-const-constructor:
ignore-abstract: false

❌ Bad:

// LINT: Prefer declaring a const constructor.
abstract interface class Extended { }

Additional Resources