0
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 3 years have passed since last update.

[Dart] Enum文字列化、自分なりの最適解

0
Last updated at Posted at 2021-09-28

こんにちは。Dart赤ん坊です。

Dartでよく言われる、Enum使いにくい問題。文字列化できないので、使い勝手が悪いんですよね。そこでextensionで使いやすくしてみました。staticも使えますし、もちろんパッケージのEnumも拡張できます。

以下のコードです。

/// サンプルEnum
enum Number { One, Two, Three }

/// サンプルEnumを拡張
extension NumberExtension on Number {
  /// Enum内個別に文字列を取得
  get name => this.toString().split(".").last;

  /// Enum全体(NumberExtension)から全てのEnum内文字列を取得
  static get names => Number.values.map((value) => value.name).toList();
}

/// 実行
main() {
  print(Number.One.name);
  // ↑結果:One
  print(NumberExtension.names);
  // ↑結果:[One, Two, Three]

  // print(Number.names);
  // これは出来ない
}

要点を解説すると、

extension NumberExtension on Number {
  get name => this.toString().split(".").last;
  static get names => Number.values.map((value) => value.name).toList();
}

extensionで、enumを拡張しています。一つ目はenumのメンバー?をtoString()した代物に"."でスプリットして、良い感じの文字列をとっています。二つ目では一つ目で作成したnameを利用して、staticでnamesを定義しています。

staticで設定したものはNumber.namesとして使用できそうなものですが、なぜかできないので、仕方なくNumberExtension.namesとして利用しています。それほど大きな面倒ではありませんので、十分利用価値はあるかと思います。

以上です。それでは。

0
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
0
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?