{

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 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.

How to print Name of Enum Constants in Dart/Flutter.

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

  • use toString and split method

For example, WEEK.MONDAY.toString() returns WEEK.MONDAY Enum, get the String version of into String WEEK.MONDAY value. Next, this string is split into two strings with . separator and last property returns 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 name as a string type and 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.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example