跳到主要内容

exhaustive_cases

稳定版
推荐
修复可用

为类似枚举类的所有常量定义 case 子句。

详情

#

对类似枚举类的实例进行 switch 语句应该穷尽所有情况。

类似枚举类被定义为具体的(非抽象)类,它们具有

  • 仅私有的非工厂构造函数
  • 两个或多个静态常量字段,其类型是封闭类,并且
  • 在定义库中没有该类的子类

务必为类似枚举类的所有常量定义 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 映射语法来配置 linter 规则,请在 linter > rules 下添加 exhaustive_cases: true

analysis_options.yaml
yaml
linter:
  rules:
    exhaustive_cases: true