Enum from String

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

    Collin Jackson's solution didn't work for me because Dart stringifies enums into EnumName.value rather than just value (for instance, Fruit.apple), and I was trying to convert the string value like apple rather than converting Fruit.apple from the get-go.

    With that in mind, this is my solution for the enum from string problem

    enum Fruit {apple, banana}
    
    Fruit getFruitFromString(String fruit) {
      fruit = 'Fruit.$fruit';
      return Fruit.values.firstWhere((f)=> f.toString() == fruit, orElse: () => null);
    }
    

提交回复
热议问题