Enum from String

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

    I had the same problem with building objects from JSON. In JSON values are strings, but I wanted enum to validate if the value is correct. I wrote this helper which works with any enum, not a specified one:

    class _EnumHelper {
    
    
     var cache = {};
    
      dynamic str2enum(e, s) {
        var o = {};
        if (!cache.containsKey(e)){
          for (dynamic i in e) {
            o[i.toString().split(".").last] = i;
          }
          cache[e] = o;
        } else {
          o = cache[e];
        }
        return o[s];
      }
    }
    
    _EnumHelper enumHelper = _EnumHelper();
    

    Usage:

    enumHelper.str2enum(Category.values, json['category']);
    

    PS. I did not use types on purpose here. enum is not type in Dart and treating it as one makes things complicated. Class is used solely for caching purposes.

提交回复
热议问题