跳到主要內容

use_enums

穩定
可修正

使用列舉 (enums) 而不是行為像列舉的類別。

詳細資訊

#

外觀像列舉的類別應宣告為 enum

務必在適當情況下使用列舉。

列舉的候選類別需符合以下條件:

  • 為具體的,
  • 為私有或僅具有私有產生器建構子,
  • 具有兩個或多個與類別類型相同的靜態常數字段,
  • 具有僅在這些靜態欄位的初始化運算式頂層調用的產生器建構子,
  • 未定義 hashCode==valuesindex
  • 未擴充 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 map 語法來設定 linter 規則,請在 linter > rules 下新增 use_enums: true

analysis_options.yaml
yaml
linter:
  rules:
    use_enums: true