跳到主要内容

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