Dart How to get the "value" of an enum
Dart 2.7 comes with new feature called Extension methods. Now you can write your own methods for Enum as simple as that!
enum Day { monday, tuesday }
extension ParseToString on Day {
String toShortString() {
return this.toString().split('.').last;
}
}
main() {
Day monday = Day.monday;
print(monday.toShortString()); //prints 'monday'
}
Bit shorter:
String day = theDay.toString().split('.').last;
Sadly, you are correct that the toString method returns "day.MONDAY"
, and not the more useful "MONDAY"
.
You can get the rest of the string as:
day theDay = day.MONDAY;
print(theDay.toString().substring(theDay.toString().indexOf('.') + 1));
Hardly convenient, admittedly.
Another way to get the enum name as a string, one which is shorter, but also less efficient because it creates an unnecessary string for first part of the string too, is:
theDay.toString().split('.').last
If performance doesn't matter, that's probably what I'd write, just for brevity.
If you want to iterate all the values, you can do it using day.values
:
for (day theDay in day.values) {
print(theDay);
}