Enum from String

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

    I think my approach is slightly different, but might be more convenient in some cases. Finally, we have parse and tryParse for enum types:

    import 'dart:mirrors';
    
    class Enum {
      static T parse(String value) {
        final T result = (reflectType(T) as ClassMirror).getField(#values)
            .reflectee.firstWhere((v)=>v.toString().split('.').last.toLowerCase() == value.toLowerCase()) as T;
        return result;
      }
    
      static T tryParse(String value, { T defaultValue }) {
        T result = defaultValue;
        try {
          result = parse(value);
        } catch(e){
          print(e);
        }
        return result;
      }
    }
    

    EDIT: this approach is NOT working in the Flutter applications, by default mirrors are blocked in the Flutter because it causes the generated packages to be very large.

提交回复
热议问题