use_enums
使用枚举而不是表现得像枚举的类。
详情
#看起来像枚举的类应该声明为 enum
。
请务必在适当情况下使用枚举。
适合作为枚举的类应满足以下条件:
- 是具体类,
- 是私有的或只有私有的生成式构造函数,
- 有两个或多个与其类类型相同的静态 const 字段,
- 其生成式构造函数仅在这些静态字段的初始化表达式的顶层被调用,
- 不定义
hashCode
、==
、values
或index
, - 不扩展
Object
以外的任何类,并且 - 在其定义库中没有声明任何子类。
要详细了解如何创建和使用这些枚举,请参阅声明增强型枚举。
不良示例
dart
class LogPriority {
static const error = LogPriority._(1, 'Error');
static const warning = LogPriority._(2, 'Warning');
static const log = LogPriority._unknown('Log');
final String prefix;
final int priority;
const LogPriority._(this.priority, this.prefix);
const LogPriority._unknown(String prefix) : this._(-1, prefix);
}
良好示例
dart
enum LogPriority {
error(1, 'Error'),
warning(2, 'Warning'),
log.unknown('Log');
final String prefix;
final int priority;
const LogPriority(this.priority, this.prefix);
const LogPriority.unknown(String prefix) : this(-1, prefix);
}
启用
#要启用 use_enums
规则,请在您的 analysis_options.yaml
文件中的 linter > rules 下添加 use_enums
analysis_options.yaml
yaml
linter:
rules:
- use_enums
如果您使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 use_enums: true
analysis_options.yaml
yaml
linter:
rules:
use_enums: true