Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum from String

Tags:

dart

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){       } 
like image 405
FPGA Avatar asked Dec 28 '14 04:12

FPGA


People also ask

How do I create an enum from a string?

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.

Can we convert string to enum?

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.

Can enum have string values?

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.


1 Answers

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); 
like image 81
Collin Jackson Avatar answered Oct 05 '22 02:10

Collin Jackson