Skip to content

late_field_never_assigned

Reports a private late variable without an initializer that is read but never assigned in its library. Assign it, give it an initializer, or remove it and the code that reads it.

Tier
blocking
Scope
Dart
Lowest preset
recommended
Fix
none

A private late field, static or not, or a private late top-level variable, without an initializer, that nothing in its library assigns and that is read. The violation is on the variable’s name.

  • Every file of the library is searched, its parts and generated parts as well. A part that cannot be read may assign it.
  • A write of any declaration of the same name counts: an assignment, an increment, a field formal parameter or a field initializer of a constructor.
  • A read is a name in the file that resolves to the variable, or the name as a word in another file of the library.

It does not report:

  • a public variable, which another library may assign;
  • a variable that is not read: avoid_late reports it with the message that nothing assigns it, and so does the analyzer’s unused_field;
  • an abstract or external variable;
  • a field of a class that declares a noSuchMethod;
  • a local late variable, which is the analyzer’s error.

The first read of such a variable throws a LateInitializationError, whatever the program does before. It is what a half-done change leaves: the code that assigned the variable went, the code that reads it stayed.

Violating
class Session {
late String _token;
String get header => 'Bearer $_token';
}
Corrected
class Session {
Session(this._token);
final String _token;
String get header => 'Bearer $_token';
}

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:

// Why it stays as written here.
// ignore: late_field_never_assigned

// ignore_for_file: assay/late_field_never_assigned silences it in a whole file, and // ignore: assay/late_field_never_assigned with the prefix works too. See Suppressions.