Nate Lockwood
Nate Lockwood

Reputation: 3665

Dart How to get the name of an enum as a String

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 name 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?

Upvotes: 225

Views: 194037

Answers (30)

mbartn
mbartn

Reputation: 3348

Dart 2.15

enum Day { monday, tuesday }

main() {
  Day monday = Day.monday;
  print(monday.name); //prints 'monday'
}

Dart 2.7 - 2.14

With new feature called Extension methods 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'
}

Upvotes: 257

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

As noted in https://medium.com/dartlang/dart-2-17-b216bfc80c5d:

With Dart 2.17 we now have general support for members on enums. That means we can add fields holding state, constructors that set that state, methods with functionality, and even override existing members.

Example:

enum Day {
   MONDAY("Monday"),
   TUESDAY("Tuesday");

  const Day(this.text);
  final String text;
}

Output:

void main() {
  const day = Day.MONDAY;
  print(day.text); /// Monday
}

For above functionality override dart version like below which target 2.17 and greater

environment:
  sdk: ">=2.17.0 <3.0.0"

Upvotes: 13

Kazi Shakib
Kazi Shakib

Reputation: 41

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

Upvotes: 0

lrn
lrn

Reputation: 71653

It used to be correct that the only way to get the source name of the enum value was through the toString method which returns "day.MONDAY", and not the more useful "MONDAY".

Since Dart 2.15, enums have exposed a extension getter which returns just the source name, so day.MONDAY.name == "MONDAY".

Since Dart 2.17, you can also add your own members to enum declarations, and choose to provide another name for a value than justits source name, e.g., with a more appropriate capitalization:

enum Day {
  monday("Monday"),
  tuesday("Tuesday"),
  // ...
  saturday("Saturday");
  sunday("Sunday");
 
  final String name;
  Day(this.name);
 
  // And other members too.
  bool get isWorkday => index < saturday.index;
}

Then you get Day.sunday.name == "Sunday" (hiding the extension name getter which would return "sunday").

Before these features, you could only get the name from the toString string, extracting the rest of the string as:

day theDay = day.MONDAY;      
print(theDay.toString().substring(theDay.toString().indexOf('.') + 1));

which was admittedly hardly convenient.

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, was:

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

Upvotes: 112

JC Wu
JC Wu

Reputation: 61

since dart 2.15 just use ".name"

enum day {monday, tuesday}
print( 'Today is ${day.monday.name}');

Upvotes: 6

CopsOnRoad
CopsOnRoad

Reputation: 267554

Update Dart 2.15:

enum Day {
  monday,
  tuesday,
}

You can use name property on the enum.

String monday = Day.monday.name; // 'monday'

Old solution:

1. Direct way:

var dayInString = describeEnum(Day.monday);
print(dayInString); // prints 'monday'

2. Using Extension:

extension DayEx on Day {
  String get name => describeEnum(this);
}

You can use it like:

void main() {
  Day monday = Day.monday;
  print(monday.name); // 'monday'
}

Upvotes: 153

Osama Remlawi
Osama Remlawi

Reputation: 2990

For those who require enum with values use this approach as Dart doesn't support this:

class MyEnumClass {
  static String get KEY_1 => 'value 1';
  static String get KEY_2 => 'value 2';
  static String get KEY_3 => 'value 3';
  ...
}

// Usage:
print(MyEnumClass.KEY_1); // value 1
print(MyEnumClass.KEY_2); // value 2
print(MyEnumClass.KEY_3); // value 3
...

And sure you may put whatever types you need.

Upvotes: 2

agent3bood
agent3bood

Reputation: 1354

Dart version 2.15 has introduced name property on enums.

Example

void main() {
  MyEnum.values.forEach((e) => print(e.name));
}

enum MyEnum { value1, Value2, VALUE2 }

Output:

value1
Value2
VALUE2

Upvotes: 1

Edie Kamau
Edie Kamau

Reputation: 270

As from Dart 2.15, you can get enum value from

print(MyEnum.one.name);
// and for getting enum from value you use
print(MyEnum.values.byName('two');

Upvotes: 3

Nae
Nae

Reputation: 15335

I use structure like below:

abstract class Strings {
  static const angry = "Dammit!";
  static const happy = "Yay!";
  static const sad = "QQ";
}

Upvotes: 9

SinaMN75
SinaMN75

Reputation: 7631

as of dart 2.15 you can use .name to get the name of enum elements.

enum day {MONDAY, TUESDAY}
print(day.MONDAY.name); // prints MONDAY

Upvotes: 1

P&#233;ter Gyarmati
P&#233;ter Gyarmati

Reputation: 1741

As from Dart version 2.15, you can access the String value of an enum constant using .name:

enum day {MONDAY, TUESDAY}

void main() {
  print('Today is ${day.MONDAY.name}');
  // Outputs: Today is MONDAY
}

You can read in detail about all the enum improvements in the official Dart 2.15 release blog post.

Upvotes: 1

kamalbanga
kamalbanga

Reputation: 2011

Since Dart 2.15, we can just do Day.monday.name, where

enum Day { monday, tuesday }

Upvotes: 1

Amr Ahmed
Amr Ahmed

Reputation: 203

dart 2.15 is now supporting this you can just type

print(day.MONDAY.name); //gives you: MONDAY

Upvotes: 1

Mahmoud Salah Eldin
Mahmoud Salah Eldin

Reputation: 2098

try this solution:

extension EnumValueToString on Enum {
  String valueAsString() {
    return describeEnum(this);
  }
}

how to used it:

enum.valueAsString()

Upvotes: 1

Luckyrat
Luckyrat

Reputation: 1455

Dart 2.15 includes an extension to make this easy:

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

Until the changes in https://github.com/dart-lang/sdk/commit/18f37dd8f3db6486f785b2c42a48dfa82de0948b are rolled out to a stable version of Dart, the other clever but more complex answers here are very useful.

Upvotes: 7

Ahmad Khan
Ahmad Khan

Reputation: 1261

One of the good ways I found in the answer is

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

But I would not suggest doing this as dart provide us a better way.

Define an extension for the enum, may be in the same file as:

enum Day {
  monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

extension DayExtension on Day {
  String get value => describeEnum(this);
}

You need to do import 'package:flutter/foundation.dart'; for this.

Upvotes: 3

Ketan Choyal
Ketan Choyal

Reputation: 93

One more way:

enum Length {
  TEN,
  TWENTY,
  THIRTY,
  NONE,
}

extension LengthValue on Length {
  static const _values = [10, 20, 30, 0];

  int get value => _values[this.index];
}

Upvotes: 4

Edie Kamau
Edie Kamau

Reputation: 270

You can check out this package enum_object

// convert enum value to string
print(TestEnum.test.enumValue);

// convert String to enum value
var enumObject = EnumObject<TestEnum>(TestEnum.values);
print(enumObject.enumFromString('test2'));```

Upvotes: 0

axunic
axunic

Reputation: 2316

Sometimes I need to separate ui-value and real-value, so I defined keys and values using Map. This way, we have more flexiblity. And by using extension (since Dart 2.7), I made a method to read its key and value.

enum Status {
  progess,
  done,
}

extension StatusExt on Status {
  static const Map<Status, String> keys = {
    Status.progess: 'progess',
    Status.done: 'done',
  };

  static const Map<Status, String> values = {
    Status.progess: 'In Progress',
    Status.done: 'Well done',
  };

  String get key => keys[this];
  String get value => values[this];

  // NEW
  static Status fromRaw(String raw) => keys.entries
      .firstWhere((e) => e.value == raw, orElse: () => null)
      ?.key;
}

// usage 1
Status status = Status.done;
String statusKey = status.key; // done
String statusValue = status.value; // Well done

// usage 2 (easy to make key and value list)
List<Status> statuses = Status.values;
List<String> statusKeys = statuses.map((e) => e.key).toList();
List<String> statusValues = statuses.map((e) => e.value).toList();

// usage 3. create Status enum from string.
Status done1 = StatusExt.fromRaw('done') // Status.done
Status done2 = StatusExt.fromRaw('dude') // null

Upvotes: 14

martinseal1987
martinseal1987

Reputation: 2419

now with null safety it looks like this

String enumToString(Object? o) => o != null ? o.toString().split('.').last : '';


T? enumFromString<T>(String key, List<T> values) {
  try {
    return values.firstWhere((v) => key == enumToString(v));
  } catch(e) {
    return null;
  }
}

Upvotes: 0

Tiago
Tiago

Reputation: 721

Create a class to help:

class Enum {
    Enum._();

    static String name(value) {
        return value.toString().split('.').last;
    }
}

and call:

Enum.name(myEnumValue);

Upvotes: 3

Tim
Tim

Reputation: 433

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

console output: Today is MONDAY

Upvotes: 24

erluxman
erluxman

Reputation: 19385

Instead of defining extension for every enum, we can define extension on object and get access to .enumValue from any enum.

void main() {

  // ❌ Without Extension ❌

  print(Countries.Cote_d_Ivoire.toString().split('.').last.replaceAll("_", " ")); // Cote d Ivoire
  print(Movies.Romance.toString().split('.').last.replaceAll("_", " ")); //Romance


  // ✅ With Extension ✅

  print(Countries.Cote_d_Ivoire.enumValue); // Cote d Ivoire
  print(Movies.Romance.enumValue); //Romance
}

enum Countries { United_States, United_Kingdom, Germany, Japan, Cote_d_Ivoire }
enum Movies { Romance, Science_Fiction, Romantic_Comedy, Martial_arts }

extension PrettyEnum on Object {
  String get enumValue => this.toString().split('.').last.replaceAll("_", " ");
}

With this, you can even define multi-word enum where words are separated by _(underscore) in its name.

Upvotes: 3

Haroon khan
Haroon khan

Reputation: 1058

enum day {MONDAY, TUESDAY}
print(day.toString().split('.')[1]);
OR
print(day.toString().split('.').last);

Upvotes: 3

Alexandr Priezzhev
Alexandr Priezzhev

Reputation: 1513

I use the functions below to get the name of the enum value and, vise versa, the enum value by the name:

String enumValueToString(Object o) => o.toString().split('.').last;

T enumValueFromString<T>(String key, Iterable<T> values) => values.firstWhere(
      (v) => v != null && key == enumValueToString(v),
      orElse: () => null,
    );

When using Dart 2.7 and newer, extension methods would work here (as well as for any other Objects):

extension EnumX on Object {
  String asString() => toString().split('.').last;
}

The implementation above is not dependant on the specific enums.

Usage examples:

enum Fruits {avocado, banana, orange}
...
final banana = enumValueFromString('banana', Fruits.values);
print(enumValueToString(banana)); // prints: "banana"
print(banana.asString()); // prints: "banana"

Edit from 2020-04-05: Added nullability checks. values parameter could be Iterable, not necessarily List. Added extensions method implementation. Removed <Fruits> annotation from the example to show that the class name duplication is not required.

Upvotes: 9

Amir.n3t
Amir.n3t

Reputation: 3439

I had the same problem in one of my projects and existing solutions were not very clean and it didn't support advanced features like json serialization/deserialization.

Flutter natively doesn't currently support enum with values, however, I managed to develop a helper package Vnum using class and reflectors implementation to overcome this issue.

Address to the repository:

https://github.com/AmirKamali/Flutter_Vnum

To answer your problem using Vnum, you could implement your code as below:

@VnumDefinition
class Visibility extends Vnum<String> {
  static const VISIBLE = const Visibility.define("VISIBLE");
  static const COLLAPSED = const Visibility.define("COLLAPSED");
  static const HIDDEN = const Visibility.define("HIDDEN");

  const Visibility.define(String fromValue) : super.define(fromValue);
  factory Visibility(String value) => Vnum.fromValue(value,Visibility);
}

You can use it like :

var visibility = Visibility('COLLAPSED');
print(visibility.value);

There's more documentation in the github repo, hope it helps you out.

Upvotes: 2

Ryan Knell
Ryan Knell

Reputation: 6322

I got so over this I made a package:

https://pub.dev/packages/enum_to_string

Also has a handy function that takes enum.ValueOne and parses it to "Value one"

Its a simple little library but its unit tested and I welcome any additions for edge cases.

Upvotes: 8

gbixahue
gbixahue

Reputation: 1413

Simplest way to get the name of an enum is a standard method from the flutter/foundation.dart

describeEnum(enumObject)

enum Day {
  monday, tuesday, wednesday, thursday, friday, saturday, sunday
}

void validateDescribeEnum() {
  assert(Day.monday.toString() == 'Day.monday');
  assert(describeEnum(Day.monday) == 'monday');
}

Upvotes: 82

Vince Varga
Vince Varga

Reputation: 6918

My approach is not fundamentally different, but might be slightly more convenient in some cases:

enum Day {
  monday,
  tuesday,
}

String dayToString(Day d) {
  return '$d'.split('.').last;
}

In Dart, you cannot customize an enum's toString method, so I think this helper function workaround is necessary and it's one of the best approaches. If you wanted to be more correct in this case, you could make the first letter of the returned string uppercase.

You could also add a dayFromString function

Day dayFromString(String s) {
  return Day.values.firstWhere((v) => dayToString(v) == s);
}

Example usage:

void main() {
  Day today = Day.monday;
  print('Today is: ${dayToString(today)}');
  Day tomorrow = dayFromString("tuesday");
  print(tomorrow is Day);
}

Upvotes: 3

Related Questions