Skip to content

private_field_never_assigned

Reports a private instance field that is read but never assigned, so every read gets null. Assign it, or remove it and the code that reads it.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
none

A private instance field that has no initializer, that nothing in its library assigns, and that is read. The violation covers the field’s name.

Every file of the library is searched, parts and generated parts included. A write to any declaration of the same name counts: an assignment, an increment, a field formal parameter, a field initializer of a constructor.

It does not report, leaving it to others:

An abstract or external field, and a field of a class that declares noSuchMethod, are not reported either. A field assigned only through a dynamic call, (holder as dynamic)._cached = 1, is reported.

It is what a half-done change leaves behind: the code that gave the field its value went, and the code that reads it stayed, handling a value that never comes. Only private fields are looked at, since only for them can every writer be seen. In the Flutter framework’s own source it found a setter that stores its handler in the field of another action, so its own getter always returns null.

Violating
class Holder {
int? _cached;
int total() => _cached ?? compute();
}
Corrected
class Holder {
int? _cached;
int total() => _cached ??= compute();
}

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 field is filled by reflection in a test.
// ignore: private_field_never_assigned
int? _cached;

// ignore_for_file: assay/private_field_never_assigned silences it in a whole file, and the prefixed // ignore: assay/private_field_never_assigned works too. See Suppressions.