use_enums
使用列舉而非行為類似列舉的類別。
此規則自 Dart 2.17 起提供。
此規則提供快速修復。
詳細資訊
#看起來像列舉的類別應該宣告為 enum
。
應該在適當的地方使用列舉。
列舉的候選類別是
- 具體的,
- 是私有的或只有私有的產生性建構子,
- 有兩個或多個與類別類型相同的靜態常數欄位,
- 具有僅在這些靜態欄位的初始化運算式最上層呼叫的產生性建構子,
- 未定義
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
除非另有說明,否則本網站上的文件反映的是 Dart 3.6.0。頁面上次更新時間為 2024-07-03。 檢視原始碼 或 回報問題。