Enum from String

前端 未结 18 2025
温柔的废话
温柔的废话 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 use this function, I think it's simple and doesn't need any kind of 'hack':

    T enumFromString(List values, String value) {
        return values.firstWhere((v) => v.toString().split('.')[1] == value,
                                 orElse: () => null);
    }
    

    You can use it like this:

    enum Test {
        value1,
        value2,
    }
    
    var test = enumFromString(Test.value, 'value2') // Test.value2
    

提交回复
热议问题