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
enum Visibility{VISIBLE,COLLAPSED,HIDDEN} Visibility visibilityFromString(String value){ return Visibility.values.firstWhere((e)=> e.toString().split('.')[1].toUpperCase()==value.toUpperCase()); } //used as Visibility x = visibilityFromString('COLLAPSED');
but it seems like i have to rewrite this function for every Enum i have, is there a way to write the same function where it takes the Enum type as parameter? i tried to but i figured out that i can't cast to Enum.
//is something with the following signiture actually possible? dynamic enumFromString(Type enumType,String value){ }
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum. TryParse () method.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
Mirrors aren't always available, but fortunately you don't need them. This is reasonably compact and should do what you want.
enum Fruit { apple, banana } // Convert to string String str = Fruit.banana.toString(); // Convert to enum Fruit f = Fruit.values.firstWhere((e) => e.toString() == str); assert(f == Fruit.banana); // it worked
Fix: As mentioned by @frostymarvelous in the comments section, this is correct implementation:
Fruit f = Fruit.values.firstWhere((e) => e.toString() == 'Fruit.' + str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With