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){
}
You can add an extension, it will still be accessed from the enum!
usage example: this answer
I had the same problem with building objects from JSON. In JSON values are strings, but I wanted enum to validate if the value is correct. I wrote this helper which works with any enum, not a specified one:
Usage:
PS. I did not use types on purpose here. enum is not type in Dart and treating it as one makes things complicated. Class is used solely for caching purposes.
There are a couple of enums packages which allowed me to get just the enum string rather than the type.value string (Apple, not Fruit.Apple).
https://pub.dartlang.org/packages/built_value (this is more up to date)
https://pub.dartlang.org/packages/enums
This is all so complicated I made a simple library that gets the job done:
https://pub.dev/packages/enum_to_string
@Collin Jackson has a very good answer IMO. I had used a for-in loop to achieve a similar result prior to finding this question. I am definitely switching to using the firstWhere method.
Expanding on his answer this is what I did to deal with removing the type from the value strings:
Maybe someone will find this useful...
Mirrors aren't always available, but fortunately you don't need them. This is reasonably compact and should do what you want.
Fix: As mentioned by @frostymarvelous in the comments section, this is correct implementation: