Enum from String

前端 未结 18 1972
温柔的废话
温柔的废话 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

    This is all so complicated I made a simple library that gets the job done:

    https://pub.dev/packages/enum_to_string

    import 'package:enum_to_string:enum_to_string.dart';
    
    enum TestEnum { testValue1 };
    
    convert(){
        String result = EnumToString.parse(TestEnum.testValue1);
        //result = 'testValue1'
    
        String resultCamelCase = EnumToString.parseCamelCase(TestEnum.testValue1);
        //result = 'Test Value 1'
    
        final result = EnumToString.fromString(TestEnum.values, "testValue1");
        // TestEnum.testValue1
    }
    
    0 讨论(0)
  • 2020-12-15 15:43

    @Collin Jackson has a very good answer IMO. I had used a for-in loop to achieve a similar result prior to finding this question. I am definitely switching to using the firstWhere method.

    Expanding on his answer this is what I did to deal with removing the type from the value strings:

    enum Fruit { apple, banana }
    
    class EnumUtil {
        static T fromStringEnum<T>(Iterable<T> values, String stringType) {
            return values.firstWhere(
                    (f)=> "${f.toString().substring(f.toString().indexOf('.')+1)}".toString()
                        == stringType, orElse: () => null);
        }
    }
    
    main() {
        Fruit result = EnumUtil.fromStringEnum(Fruit.values, "apple");
        assert(result == Fruit.apple);
    }
    

    Maybe someone will find this useful...

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-12-15 15:47

    Here is the function that converts given string to enum type:

    EnumType enumTypeFromString(String typeString) => EnumType.values
        .firstWhere((type) => type.toString() == "EnumType." + typeString);
    

    And here is how you convert given enum type to string:

    String enumTypeToString(EnumType type) => type.toString().split(".")[1];
    
    0 讨论(0)
  • 2020-12-15 15:49

    My solution is identical to Rob C's solution but without string interpolation:

    T enumFromString<T>(Iterable<T> values, String value) {
      return values.firstWhere((type) => type.toString().split(".").last == value,
          orElse: () => null);
    }
    
    0 讨论(0)
  • 2020-12-15 15:49

    Your enum

    enum Day {
      monday,
      tuesday,
    }
    

    Add this extension (need a import 'package:flutter/foundation.dart';)

    extension EnumEx on String {
      Day toEnum() => Day.values.firstWhere((d) => describeEnum(d) == toLowerCase());
    }
    

    Usage:

    void main() {
      String s = 'monday'; // String
      Day monday = s.toEnum(); // Converted to enum
    }
    
    0 讨论(0)
提交回复
热议问题