exhaustive_cases
Define case clauses for all constants in enum-like classes.
This rule is available as of Dart 2.9.
Rule sets: recommended, flutter
This rule has a quick fix available.
Details
#Switching on instances of enum-like classes should be exhaustive.
Enum-like classes are defined as concrete (non-abstract) classes that have:
- only private non-factory constructors
- two or more static const fields whose type is the enclosing class and
- no subclasses of the class in the defining library
DO define case clauses for all constants in enum-like classes.
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;
}
}
Usage
#To enable the exhaustive_cases
rule, add exhaustive_cases
under linter > rules in your analysis_options.yaml
file:
linter:
rules:
- exhaustive_cases
Unless stated otherwise, the documentation on this site reflects Dart 3.5.4. Page last updated on 2024-07-03. View source or report an issue.