Skip to main content

prefer-declaring-const-constructor

added in: 1.0.0
⚙️🛠

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

Additional resources:

⚙️ Config

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

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

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

Example

❌ Bad:

// LINT
class MyException implements Exception {}

class Square {
Square(this.sideLength); // LINT

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

final double sideLength;
}

class Square {
Square(this.sideLength, this.color); // LINT

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;
}