Is there any way to convert a enum to a string and back, without knowing the specific enum. The enums also share a mixin.
For example:
mixin TestMixin {
String get value;
}
enum FirstEnum with TestMixin {
foo("bar");
const FirstEnum(this.value);
@override
final String value;
}
enum SecondEnum with TestMixin {
two("car");
const SecondEnum(this.value);
@override
final String value;
}
I now have two enums and want to convert them to a string and back, like this
FirstEnum first = FirstEnum.foo;
SecondEnum second = SecondEnum.two;
String firstString = enumToString(first);
String secondString = enumToString(second); // -> enums as strings
Enum firstAgain = stringToEnum(firstString); // firstAgain == first
Enum secondAgain = stringToEnum(secondString); // secondAgain == second
String enumToString(Enum inp) {
// ???
}
Enum stringToEnum(String inp) {
// ???
}
Is there any way of doing this in dart? As far as i can tell you can do reflection with reflectable
but I have not gotten this to work.
2
Answers
You can use
enum.name
property to convert enum to a String and back.For converting String back to enum, you must ensure that the input must equals one of the enum.name or it will not work. You must also know the name of the list of enum here.
What I usually does to solve this is simply:
toString
method of my enum.fromString
method inside the enum.The code will look something like this:
The usage would look like this:
I find this is as a straight and concise way, since I’m not using a global method to handle the conversions, and all methods are abstracted into the particular enum class itself.