use_enums
列挙型のように振る舞うクラスではなく、列挙型を使用してください。
このルールは、Dart 2.17以降で使用できます。
このルールにはクイックフィックスが用意されています。
詳細
#列挙型のように見えるクラスは、enum
として宣言する必要があります。
適切な場合は、列挙型を使用してください。
列挙型の候補となるのは、以下の条件を満たすクラスです。
- 具体的なクラスである。
- プライベートであるか、プライベートな生成コンストラクタのみを持つ。
- クラスと同じ型を持つ2つ以上の静的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
特に明記されていない限り、このサイトのドキュメントはDart 3.5.3を反映しています。最終更新日:2024年7月3日。 ソースを表示 または 問題を報告する。