Add methods or values to enum in dart

前端 未结 8 957
刺人心
刺人心 2020-12-14 05:21

In java when you are defining an enum you can do something similar to the following. Is this possible in Dart?

enum blah {
  one(1), two(2);
  final num valu         


        
相关标签:
8条回答
  • 2020-12-14 06:12

    Dart enums are used only for the simplest cases. If you need more powerful or more flexible enums, use classes with static const fields like shown in https://stackoverflow.com/a/15854550/217408

    This way you can add whatever you need.

    0 讨论(0)
  • 2020-12-14 06:17

    extension is good, but it cannot add static methods. If you want to do something like MyType.parse(string), consider using a class with static const fields instead (as Günter Zöchbauer suggested before).

    Here is an example

    class PaymentMethod {
      final String string;
      const PaymentMethod._(this.string);
    
      static const online = PaymentMethod._('online');
      static const transfer = PaymentMethod._('transfer');
      static const cash = PaymentMethod._('cash');
    
      static const values = [online, transfer, cash];
    
      static PaymentMethod parse(String value) {
        switch (value) {
          case 'online':
            return PaymentMethod.online;
            break;
          case 'transfer':
            return PaymentMethod.transfer;
            break;
          case 'cash':
            return PaymentMethod.cash;
          default:
            print('got error, invalid payment type $value');
            return null;
        }
      }
    
      @override
      String toString() {
        return 'PaymentMethod.$string';
      }
    }
    

    I found this much handier than using a helper function.

    final method = PaymentMethod.parse('online');
    assert(method == PaymentMethod.online);
    
    0 讨论(0)
提交回复
热议问题