use_enums
使用枚举而不是行为类似于枚举的类。
详情
#看起来像枚举的类应该声明为枚举。
请在适当的地方使用枚举。
枚举的候选类是那些
- 是具体的,
- 是私有的或只有私有生成构造函数,
- 有两个或多个与该类类型相同的静态常量字段,
- 具有仅在这些静态字段的初始化表达式的顶层调用的生成构造函数,
- 不定义 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
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面最后更新于 2025-03-07。 查看源代码 或 报告问题。