How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

This tutorial shows multiple ways to get Enum Name as String.

It Converts the enum constant into String in Dart and Flutter programming.

Consider Enum declaration

enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
void main() {
  WEEK thursday = WEEK.THURSDAY;
  print(WEEK.MONDAY.toString()); //WEEK.MONDAY
  print(WEEK.MONDAY.index); // zero
  print(WEEK.MONDAY.runtimeType); // WEEK
}

From the above example, Printing Enum values return the value itself of type Enum. For example, WEEK.MONDAY.toString() returns WEEK.MONDAY. i.e Week type

This tutorial shows how to print Enum value as a name i.e MONDAY.

Convert Enum to String in Dart/Flutter

There are multiple ways we can get the Enum constant’s name in a string.

How to print the Name of Enum Constants

  • use the toString and split method

For example, WEEK.MONDAY.toString() returns WEEK.MONDAY Enum, get the String version of into String WEEK.MONDAYvalue. Next, this string is split into two strings with a . separator, and the last property returns the last element i.e MONDAY.

Here is an example to convert Enum to String in Dart.

enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

void main() {
  WEEK thursday = WEEK.THURSDAY;
  String name = thursday.toString().split('.').last;

  print(name); //THURSDAY
  print(name.runtimeType); //String
}
  • use name property.

Inbuilt property name returns an enum object as a string type and its name value.

Here is an example to convert Enum to String in Dart.

enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

void main() {
  WEEK thursday = WEEK.THURSDAY;

  print(thursday.name); // THURSDAY
  print(thursday.name.runtimeType); // String
}

Conclusion

To summarize,

Learned how to convert Enum Constant into String name in two ways

  • Enum name property
  • toString() and split methods