exhaustive_ cases
Learn about the exhaustive_cases linter rule.
Define case clauses for all constants in enum-like types.
Details
#Switching on instances of enum-like types should cover all known constants.
Enum-like types are classes or extension types that have:
- only private non-factory constructors
- two or more static const fields whose type is the enclosing type
In addition, enum-like classes are concrete (non-abstract) and have no subclasses in the defining library.
DO define case clauses for all constants in enum-like types.
Extension types can also be enum-like:
extension type const E._(int value) {
static const E a = E._(1);
static const E b = E._(2);
}
void f(E e) {
switch (e) { // LINT
case E.a:
print('a');
}
}
BAD:
class EnumLike {
final int i;
const EnumLike._(this.i);
static const e = EnumLike._(1);
static const f = EnumLike._(2);
static const g = EnumLike._(3);
}
void bad(EnumLike e) {
// Missing case.
switch(e) { // LINT
case EnumLike.e :
print('e');
break;
case EnumLike.f :
print('f');
break;
}
}
GOOD:
class EnumLike {
final int i;
const EnumLike._(this.i);
static const e = EnumLike._(1);
static const f = EnumLike._(2);
static const g = EnumLike._(3);
}
void ok(EnumLike e) {
// All cases covered.
switch(e) { // OK
case EnumLike.e :
print('e');
break;
case EnumLike.f :
print('f');
break;
case EnumLike.g :
print('g');
break;
}
}
Enable
#
To enable the exhaustive_cases rule, add exhaustive_cases under
linter > rules in your analysis_options.yaml
file:
linter:
rules:
- exhaustive_cases
If you're instead using the YAML map syntax to configure linter rules,
add exhaustive_cases: true under linter > rules:
linter:
rules:
exhaustive_cases: true
Unless stated otherwise, the documentation on this site reflects Dart 3.13.3. Report an issue.