19
6

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.

DartAdvent Calendar 2019

Day 16

DartのExtensionでStatic methodを使う方法

Last updated at Posted at 2019-12-16

株式会社TenxiaのCEOの岡部(Twitter)です。

ついにFlutterのStableがDart2.7になり、待望のExtensionが使えるようになりました。

ExtensionでStatic methodを使う方法で若干詰まったので、メモがてら記事にしておきます。

直感的な方法だと参照出来ない

enum Sex {
  male,
  female,
  others,
}

extension SexExtension on Sex {
  static Sex fromString(String text) {
    switch(text) {
      case 'male':
        return Sex.male;
      case 'female':
        return Sex.female;
      default:
        return Sex.others;
    }
  }
}


main() {
  print(Sex.fromString('male'));
  /// Error compiling to JavaScript:
  /// main.dart:22:13:
  /// Error: Enums can't be instantiated.
  /// print(Sex.fromString('male'));
  ///            ^^^^^^^^^^
  /// Error: Compilation failed.
}


こっちに生えてる

main() {
  print(SexExtension.fromString('male'));
  /// => Sex.male
}

良かったですね。

参考: https://github.com/dart-lang/language/issues/723#issuecomment-562582406

19
6
0

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
19
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?