prefer_const_constructors
Prefer const
with constant constructors.
Details
#PREFER using const
for instantiating constant constructors.
If a constructor can be invoked as const to produce a canonicalized instance, it's preferable to do so.
BAD:
dart
class A {
const A();
}
void accessA() {
A a = new A();
}
GOOD:
dart
class A {
const A();
}
void accessA() {
A a = const A();
}
GOOD:
dart
class A {
final int x;
const A(this.x);
}
A foo(int x) => new A(x);
Enable
#To enable the prefer_const_constructors
rule, add prefer_const_constructors
under linter > rules in your analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_const_constructors
If you're instead using the YAML map syntax to configure linter rules, add prefer_const_constructors: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
prefer_const_constructors: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.