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