Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 380
Suragch Avatar asked Nov 18 '20 04:11

Suragch


People also ask

Can you loop through an enum?

An enum can be looped through using Enum. GetNames<TEnum>() , Enum.

How do Dart strings compare to enums?

If we want to compare with string we need to call toString() function. Some of you might think enum value returns a number. If we want to use it as a number value we need to use the index getter property. It always starts from 0.

How do you use enum flutters?

An enumeration in Dart is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over. Every value of an enumeration has an index. The first value has an index of 0.


1 Answers

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
like image 177
Suragch Avatar answered Nov 15 '22 11:11

Suragch