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