Skip to content

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 const before the constructor

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, not late, 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 const and 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: const would change no call;
  • a class that is @immutable, or extends or implements one, a widget among them. The SDK lint prefer_const_constructors_in_immutables covers those, and is on in recommended.

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.

Violating
class _Entry {
_Entry(this.key, this.value);
final String key;
final int value;
}
final empty = _Entry('', 0);
Corrected
class _Entry {
const _Entry(this.key, this.value);
final String key;
final int value;
}
final empty = _Entry('', 0);

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.

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.