Enum from String

前端 未结 18 2066
温柔的废话
温柔的废话 2020-12-15 14:54

I have an Enum and a function to create it from a String because i couldn\'t find a built in way to do it



        
18条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 15:43

    enum in Dart just has too many limitations. The extension method could add methods to the instances, but not static methods.

    I really wanted to be able to do something like MyType.parse(myString), so eventually resolved to use manually defined classes instead of enums. With some wiring, it is almost functionally equivalent to enum but could be modified more easily.

    class OrderType {
      final String string;
      const OrderType._(this.string);
    
      static const delivery = OrderType._('delivery');
      static const pickup = OrderType._('pickup');
    
      static const values = [delivery, pickup];
    
      static OrderType parse(String value) {
        switch (value) {
          case 'delivery':
            return OrderType.delivery;
            break;
          case 'pickup':
            return OrderType.pickup;
            break;
          default:
            print('got error, invalid order type $value');
            return null;
        }
      }
    
      @override
      String toString() {
        return 'OrderType.$string';
      }
    }
    
    // parse from string
    final OrderType type = OrderType.parse('delivery');
    assert(type == OrderType.delivery);
    assert(type.string == 'delivery');
    

提交回复
热议问题