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.
An enum can be looped through using Enum. GetNames<TEnum>() , Enum.
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.
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.
Given an enum like so,
enum MyEnum {
horse,
cow,
camel,
sheep,
goat,
}
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With