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
What it reports
Section titled “What it reports”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
forloop, or of aforin a collection literal; - a parameter of a function literal, such as the index a list builder or a tab’s
onTapis 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.
Example
Section titled “Example”Status statusOf(Map<String, Object?> json) => Status.values[json['status'] as int];Status statusOf(Map<String, Object?> json) => Status.values.byName(json['status'] as String);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 codes come from a table that follows the declaration.// ignore: enum_value_by_indexfinal 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.