Skip to content

enum_compared_in_if_chain

Reports an if and else if chain that compares one value with values of its enum. Use a switch instead.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

A chain of if and else if with at least two conditions, each comparing one value with == to a value of its enum, or such comparisons joined by ||. The violation is on the head of the chain, from if to the bracket that closes its condition.

  • The value must be the same in every condition, and repeatable: a local, a parameter, a final field.
  • Enum values may be written with the enum’s name or as dot shorthands, on either side of ==.

It does not report:

  • a single if;
  • a chain in which any condition tests something else, or that compares two different values;
  • an if-case;
  • a value read through a getter or a call, which may change between the conditions;
  • a chain that is the else of an if that tests something else.

A switch on an enum names each value once, and the compiler tells you which values it does not handle. A chain of comparisons says nothing when a value is added to the enum: the new value falls into the last else, or through every branch.

Violating
if (mode == Mode.dark) {
return dark;
} else if (mode == Mode.light) {
return light;
}
return system;
Corrected
return switch (mode) {
Mode.dark => dark,
Mode.light => light,
Mode.system => system,
};

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

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