constructor_could_be_const
Reports a private constructor that could be const, where a call in the same file gives it only constants. Add const.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- strict
- Fix
- writes
constbefore the constructor
What it reports
Section titled “What it reports”A constructor that only the library of its class can call, that could be const but is not, and that a call in the same file gives constants only. Only the library can call a constructor with a private name, or any constructor of a private class.
It is reported only where const compiles:
- it is a generative constructor of a class, without a body, whose initializers give fields parameters or constants;
- every instance field is
final, notlate, and starts as a constant if it has an initializer; - no mixin of the class has an instance field;
- the superclass constructor it calls, or the one it redirects to, is
constand is given parameters and constants only.
It does not report:
- a constructor with an
assert; - the parameterless constructor of a class of static members only, which is there to forbid instances;
- a constructor that no call in the file gives constants only:
constwould change no call; - a class that is
@immutable, or extends or implements one, a widget among them. The SDK lintprefer_const_constructors_in_immutablescovers those, and is on inrecommended.
Without const on the constructor, no caller can make a constant of the class, and only the class can add it.
A public constructor is not reported. There const is also a promise to every caller outside the library that the class stays constant, which only its writer can make.
Example
Section titled “Example”class _Entry { _Entry(this.key, this.value); final String key; final int value;}
final empty = _Entry('', 0);class _Entry { const _Entry(this.key, this.value); final String key; final int value;}
final empty = _Entry('', 0);Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The class gains a mutable cache in the next release.// ignore: assay/constructor_could_be_const// ignore_for_file: assay/constructor_could_be_const silences it in a whole file, and // ignore: constructor_could_be_const without the prefix works too. See Suppressions.