Skip to main content

prefer-switch-with-enums

added in: 1.12.0
⚙️
Pro+
preset: recommended

Suggests to use a switch statement or expression instead of conditionals with multiple enum values.

When it comes to enum values, the analyzer warns you when a new enum value is not covered by a switch case. This feature is not available for if statements and conditional expressions. Therefore using switches where possible can reduce the number of potential bugs.

⚙️ Config

Set ignore-contains (default is false) to exclude .contains() (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-switch-with-enums:
ignore-contains: false

Example

❌ Bad:

void fn(MyEnum value) {
// LINT: Prefer switch statement/expression when checking enum values.
if (value == MyEnum.first) {
print(value);
} else if (value == MyEnum.second) {
print(value);
} else if (value == MyEnum.third) {
print(value);
}

// LINT: Prefer switch statement/expression when checking enum values.
if (value == MyEnum.first || value == MyEnum.second) {
} else {}

final possibleValues = {MyEnum.first, MyEnum.second};
// LINT: Prefer switch statement/expression when checking enum values.
if (possibleValues.contains(value)) {}
}

enum MyEnum {
first,
second,
third,
}

✅ Good:

void fn(MyEnum value) {
switch (value) {
case MyEnum.first:
...

case MyEnum.second:
...

case MyEnum.third:
...
}
}

Example with "ignore-contains"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-switch-with-enums:
ignore-contains: true

✅ Good:

void fn(MyEnum value) {
final possibleValues = {MyEnum.first, MyEnum.second};
if (possibleValues.contains(value)) {} // Correct, ignored
}