prefer-switch-with-enums
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()
from checks.
dart_code_metrics:
...
rules:
...
- prefer-switch-with-enums:
ignore-contains: false
Example
❌ Bad:
void fn(MyEnum value) {
// LINT
if (value == MyEnum.first) {
print(value);
} else if (value == MyEnum.second) {
print(value);
} else if (value == MyEnum.third) {
print(value);
}
// LINT
if (value == MyEnum.first || value == MyEnum.second) {
} else {}
final possibleValues = {MyEnum.first, MyEnum.second};
// LINT
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:
...
}
}
enum MyEnum {
first,
second,
third,
}