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
What it reports
Section titled “What it reports”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:
- a field that is not read: the analyzer’s
unused_field; - a
latefield:avoid_late, whose message then says that nothing assigns it; - a static field:
avoid_global_mutable_state; - a field with an initializer:
prefer_final_fields.
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.
Example
Section titled “Example”class Holder { int? _cached;
int total() => _cached ?? compute();}class Holder { int? _cached;
int total() => _cached ??= compute();}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 field is filled by reflection in a test.// ignore: private_field_never_assignedint? _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.