Skip to content

enum_value_by_index

Reports an enum value read by its position from a number that comes from elsewhere. Store the name and read it with values.byName instead.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
none

A value of an enum read by its position from a number that comes from elsewhere. The violation is on the reading:

  • Status.values[json['status'] as int];
  • Status.values[prefs.getInt('status')!];
  • Status.values.elementAt(code);
  • values[stored] inside the enum.

It does not report an index that is a position, not a stored number:

  • a literal, Status.values[0];
  • the variable of a for loop, or of a for in a collection literal;
  • a parameter of a function literal, such as the index a list builder or a tab’s onTap is given;
  • an expression that reads a name ending in index, in any case: mode.index + 1, controller.index, _selectedIndex.

A number that a parameter of a named function gives is reported, even where it is a position.

A stored index means a value only as long as the enum keeps its order. Insert a value or reorder the enum, and every stored number means another value. Nothing fails: the code just reads wrong values from then on. A stored name, read with values.byName, does not depend on the order.

The rule is advisory because some indexes are positions in the user interface, not stored data.

Violating
Status statusOf(Map<String, Object?> json) => Status.values[json['status'] as int];
Corrected
Status statusOf(Map<String, Object?> json) =>
Status.values.byName(json['status'] as String);

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 codes come from a table that follows the declaration.
// ignore: enum_value_by_index
final mode = Mode.values[code];

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