Dart How to get the "value" of an enum

Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the value of the enum as a string such as can be done with Java but cannot.

For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"

enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');

Am I correct that to get just 'MONDAY' I will need to parse the string?


Solution 1:

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'
}

Solution 2:

Bit shorter:

String day = theDay.toString().split('.').last;

Solution 3:

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);
}