exhaustive_cases
Define case clauses for all constants in enum-like classes.
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:
dart
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:
dart
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:
analysis_options.yaml
yaml
linter:
rules:
- exhaustive_cases
If you're instead using the YAML map syntax to configure linter rules,
add exhaustive_cases: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
exhaustive_cases: true
除非另有说明,文档之所提及适用于 Dart 3.7.1 版本,本页面最后更新时间: 2025-01-27。 查看文档源码 或者 报告页面问题。