use_enums
Use enums rather than classes that behave like enums.
此规则自 Dart 2.17 版本起可用。
此规则提供 快速修复 。
详情
#Classes that look like enumerations should be declared as enums.
DO use enums where appropriate.
Candidates for enums are classes that:
- are concrete,
- are private or have only private generative constructors,
- have two or more static const fields with the same type as the class,
- have generative constructors that are only invoked at the top-level of the initialization expression of these static fields,
- do not define
hashCode,==,valuesorindex, - do not extend any class other than
Object, and - have no subclasses declared in the defining library.
To learn more about creating and using these enums, check out Declaring enhanced enums.
BAD:
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);
}GOOD:
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除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.