exhaustive_cases
為類列舉中的所有常量定義 case 子句。
詳情
#對類列舉例項進行 switch 操作應是窮盡的。
類列舉定義為具體的(非抽象)類,且滿足以下條件:
- 只有私有的非工廠建構函式
- 兩個或更多型別為封裝類本身的靜態 const 欄位,並且
- 定義庫中沒有該類的子類
務必為類列舉中的所有常量定義 case 子句。
錯誤示例
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;
}
}正確示例
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;
}
}啟用
#要啟用 exhaustive_cases 規則,請在你的 analysis_options.yaml 檔案中,在 linter > rules 下新增 exhaustive_cases
analysis_options.yaml
yaml
linter:
rules:
- exhaustive_cases如果你改為使用 YAML map 語法配置 Linter 規則,請在 linter > rules 下新增 exhaustive_cases: true
analysis_options.yaml
yaml
linter:
rules:
exhaustive_cases: true