Suragch
Suragch

Reputation: 511956

How to loop over an enum in Dart

I have a Dart enum in my Flutter project like this:

enum RepeatState {
  playSongOnce,
  repeatSong,
  repeatPlaylist,
}

If I have some random enum state like RepeatState.repeatSong, how do I iterate to the next enum (without doing something like mapping them with a switch statement)?

I found the answer with the help of this, this and this, so I'm posting it below.

Upvotes: 24

Views: 21099

Answers (3)

lomza
lomza

Reputation: 9716

With Flutter 3.0 enums, you could have extra functions to get all enum values or to get one by string value, for example:

enum RepeatState {
  playSongOnce,
  repeatSong,
  repeatPlaylist;

  static RepeatState getEnum(String name) => RepeatState.values.firstWhere((element) => element.name == name);
  static List<String> stringValues() => RepeatState.values.map((e) => e.name).toList();
}

In order to get the String value: StatusEnum.purple.value

And calling our extra functions:

print('${RepeatState.stringValues()}');
print('${RepeatState.getEnum('repeatSong')}');

Gives us:

I/flutter (14298): [playSongOnce, repeatSong, repeatPlaylist]
I/flutter (14298): RepeatState.repeatSong

More on new enums is here.

Upvotes: 4

Sandun Perera
Sandun Perera

Reputation: 571

enum Fruites { Mango, Banana, Cherry, Avacado, Papaya }

void main() {
  Fruites.values.forEach((name) {
    print(name);
  });
}

Output:

Fruites.Mango
Fruites.Banana
Fruites.Cherry
Fruites.Avacado
Fruites.Papaya

Take name part only

print(name.toString().split('.').elementAt(1));

Output:

Mango
Banana
Cherry
Avacado
Papaya

Upvotes: 9

Suragch
Suragch

Reputation: 511956

Given an enum like so,

enum MyEnum {
  horse,
  cow,
  camel,
  sheep,
  goat,
}

Looping over the values of an enum

You can iterate over the values of the enum by using the values property:

for (var value in MyEnum.values) {
  print(value);
}

// MyEnum.horse
// MyEnum.cow
// MyEnum.camel
// MyEnum.sheep
// MyEnum.goat

Converting between a value and its index

Each value has an index:

int index = MyEnum.horse.index; // 0

And you can convert an index back to an enum using subscript notation:

MyEnum value = MyEnum.values[0]; // MyEnum.horse

Finding the next enum value

Combining these facts, you can loop over the values of an enum to find the next value like so:

MyEnum nextEnum(MyEnum value) {
  final nextIndex = (value.index + 1) % MyEnum.values.length;
  return MyEnum.values[nextIndex];
}

Using the modulo operator handles even when the index is at the end of the enum value list:

MyEnum nextValue = nextEnum(MyEnum.goat); // MyEnum.horse

Upvotes: 60

Related Questions