0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dartにおける Raw Value

Posted at

本記事のきっかけ

毎回のようにFlutterで値つきenumの実装を方法を調べているので記事に残しました!

Raw Valueとは

Swiftにおけるいわゆる値つきenum
https://www.hackingwithswift.com/sixty/2/9/enum-associated-values

これと同様な機能を実現する方法としてDart2.17から追加されてる。

使い方

SwiftとDartを比べてみる

Swiftの書き方

例として認証エラーのenumを考える

enum AuthException:String {
    case  invalidEmail = 'invalid email'
    case  invalidEmail = 'password is too weak'
    case  wrongPassword = 'wrong password'

    let error = .invalidEmail.rawValue // String型の`invalid email`が取得できる

    
}

注意点としてenumがサポートしてるプリミティブ型の必要あり。

Dartの書き方

enum AuthException {
    invalidEmail('invalid email)',
    invalidEmail('password is too weak'),
    wrongPassword('wrong password');

    const AuthException(this.message);// const コンストラクタを追加
    final String message;// final プロパティを追加
}

const error = AuthException.invalidEmail; // String型の `invalid email`が取得できる

ぜひ参考にしてみてください

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?