2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Dartでenumの値を指定する

Last updated at Posted at 2022-04-07

2022/05/13追記

Dart 2.1.17から標準で以下の書き方ができるようになりました。 (@Cat_sushi ありがとうございます)

enum Water {
  frozen(32),
  lukewarm(100),
  boiling(212),
}

参考
https://medium.com/dartlang/dart-2-17-b216bfc80c5d#72da

旧記事

TypeScriptとかだと、↓こんな感じにできて便利なんですが、DartだとExtensionを作る必要があるようです。
数値の方がDBに格納されている場合に、enumの並び順を変更して値が変わると困るので。

enum MyColor {
 red = 1,
 green = 100,
}

enum MyColor {
  red,
  green
}

extension MyColorExtension on MyColor {
  int get id {
    switch (this) {
      case MyColor.red:
        return 1;
      case MyColor.green:
        return 100;
    }
  }
}
2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?