How to loop over an enum in Dart

3,908

Solution 1

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

Solution 2

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
Share:
3,908
Suragch
Author by

Suragch

Read my story here: Programming was my god

Updated on December 25, 2022

Comments

  • Suragch
    Suragch over 1 year

    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.