{

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.

How to: Convert Enum to String in dart or flutter

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 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 enum object as a string type and it’s 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.