prefer-declaring-const-constructor
added in: 1.0.0
performance
Warns when a class with no non-final fields has a non-constant constructor declaration.
Additional resources:
- https://github.com/dart-lang/linter/issues/3983
- https://stackoverflow.com/a/57618161
- https://medium.com/nerd-for-tech/flutter-performance-analysis-of-const-constructor-d2a72fd8a043
⚙️ Config
Set allow-one
(default is false
) to allow at least one const constructor.
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;
}