Skip to main content

prefer-specific-cases-first

dart 3.0+
has auto-fix
pro+

Warns when a more specific switch case is placed after a more general one.

This can lead to the more specific case to never match.

Example

❌ Bad:

void fn(SomeClass param) {
final value = switch (param) {
Sub() => 1,
// LINT: This case is more specific than one of the above and will never match. Try moving it higher.
Sub() when param.value.isEmpty => 2,
_ => 3,
};

switch (param) {
case Sub():
print(1);

// LINT: This case is more specific than one of the above and will never match. Try moving it higher.
case Sub() when param.value.isEmpty:
print(2);

case _:
print(3);
}
}

class SomeClass {
final String value;

const SomeClass(this.value);
}

class Sub extends SomeClass {
const Sub(super.value);
}

✅ Good:

void fn(SomeClass param) {
final value = switch (param) {
Sub() when param.value.isEmpty => 2,
Sub() => 1,
_ => 3,
};

switch (param) {
case Sub() when param.value.isEmpty:
print(2);

case Sub():
print(1);

case _:
print(3);
}
}

Additional Resources