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:
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;
}
}
Usage
#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
除非另有说明,文档之所提及适用于 Dart 3.5.3 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。