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){
}
I think my approach is slightly different, but might be more convenient in some cases. Finally, we have parse and tryParse for enum types:
EDIT: this approach is NOT working in the Flutter applications, by default mirrors are blocked in the Flutter because it causes the generated packages to be very large.
Here is the function that converts given string to enum type:
And here is how you convert given enum type to string:
My solution is identical to Rob C's solution but without string interpolation:
I improved Collin Jackson's answer using Dart 2.7 Extension Methods to make it more elegant.
Collin Jackson's solution didn't work for me because Dart stringifies enums into
EnumName.value
rather than justvalue
(for instance,Fruit.apple
), and I was trying to convert the string value likeapple
rather than convertingFruit.apple
from the get-go.With that in mind, this is my solution for the enum from string problem
Using mirrors you could force some behaviour. I had two ideas in mind. Unfortunately Dart does not support typed functions:
Outputs: