Get Enum from a String in flutter Dart

I wanted to get the correspondent enum value from a string field. Let’s say I have defined enum Fruit.

enum Fruit {apple, banana}

In the JSON payload of an API call, I’m getting string value of the enum. So I want to convert it to the correct enum value. This is how I did in my flutter application.

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

 


Leave a Reply

Your email address will not be published. Required fields are marked *