Skip to content

incomplete_enum_map_lookup

Reports an asserted lookup (! or a cast) in an enum map that leaves out keys the lookup can be given. Give the map an entry for every constant, or use an exhaustive switch.

Tier
blocking
Scope
Dart
Lowest preset
recommended
Fix
none

A lookup that asserts its entry is there, with a ! after it or a cast to a type that is not nullable. The map is a literal whose keys are all constants of one enum and leave some of them out, and the key can be one of those left out:

  • a constant of the enum that the map leaves out;
  • a parameter of a function or a method, or a field or a getter, of the enum type;
  • the variable of a for over the enum’s values, or a parameter of a function literal handed directly to a method of the enum’s values.

The map is held by a variable that nothing changes: a const one, or a final local, private field or private top-level variable, in a library of one file, that is only read (through an index or a member that only reads, such as containsKey, keys, values).

The violation is on the lookup. Its message names the map and the first three missing constants, and counts the others.

It does not report:

  • a complete map;
  • a lookup with ??, or one that is not asserted;
  • a key that is a local holding what something gave;
  • a key under a condition that names the key or the map (containsKey, status == …), in a case of a switch on the key, or after an if of the same block that names it;
  • a map that may be changed elsewhere: a public final, or one written to.

A sparse enum map read with ?? is a sound design; the defect is the assertion. For each missing constant, the ! throws. An exhaustive switch on the value makes the compiler check that every constant is handled, and tells you again when a constant is added.

Violating
enum Status { draft, active, archived }
const _labels = {Status.draft: 'Draft', Status.active: 'Active'};
String label(Status status) => _labels[status]!;
Corrected
enum Status { draft, active, archived }
String label(Status status) => switch (status) {
Status.draft => 'Draft',
Status.active => 'Active',
Status.archived => 'Archived',
};

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: incomplete_enum_map_lookup

A suppression of this rule at the lookup hides the place: the ! is not reported by avoid_non_null_assertion instead. // ignore_for_file: assay/incomplete_enum_map_lookup silences it in a whole file, and // ignore: assay/incomplete_enum_map_lookup with the prefix works too. See Suppressions.