Enum from String

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

    another variant, how it might be solved:

    enum MyEnum {
      value1,
      value2,
    }
    
    extension MyEnumX on MyEnum {
      String get asString {
        switch (this) {
          case MyEnum.value1:
            return _keyValue1;
          case MyEnum.value2:
            return _keyValue2;
        }
        throw Exception("unsupported type");
      }
    
      MyEnum fromString(String string) {
        switch (string) {
          case _keyValue1:
            return MyEnum.value1;
          case _keyValue2:
            return MyEnum.value2;
        }
        throw Exception("unsupported type");
      }
    }
    
    const String _keyValue1 = "value1";
    const String _keyValue2 = "value2";
    
    void main() {
        String string = MyEnum.value1.asString;
        MyEnum myEnum = MyEnum.value1.fromString(string);
    }
    

提交回复
热议问题