How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

  • How to loop enum constants in Dart?
  • How to get Enum with index in Dart?

How to loop enum constants and index in Dart?

Enum provides a values method that returns an array of Enum constants.

You can iterate the enum using the following variations of for loop

  • for in loop: Iterate each element and print to console
  • forEach loop: Iterate each element and use element and index, prints to console. Here is an example code
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

void main() {
  var weeks = WEEK.values;
  // using for in loop
  for (var value in weeks) {
    print(value);
  }
  // using for each loop
  weeks.forEach((name) {
    print('$name : ${name.index}');
  });
}

Output:

WEEK.MONDAY
WEEK.TUESDAY
WEEK.WEDNESDAY
WEEK.THURSDAY
WEEK.FRIDAY
WEEK.SATURDAY
WEEK.SUNDAY
WEEK.MONDAY : 0
WEEK.TUESDAY : 1
WEEK.WEDNESDAY : 2
WEEK.THURSDAY : 3
WEEK.FRIDAY : 4
WEEK.SATURDAY : 5
WEEK.SUNDAY : 6

From the above output, Printing an Enum object prints Enum with a constant value.

If you want to print only constant values, Add the extension method for printing the string version by a split with the . operator

enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

extension ToString on WEEK {
  String printName() {
    return this.toString().split('.').last;
  }
}

void main() {
  var weeks = WEEK.values;
  // using for in loop
  for (var value in weeks) {
    print(value.printName());
  }
}

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

How to get Enum with index in Dart

Enum class provides an index method that returns the position of an Enum constant (start from zero indexes)

Here is an example to get the Index for Enum constants.

enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

void main() {
  int index = WEEK.SUNDAY.index;
  print(index); //6
}

Another way is to get Enum using an index. pass an index to values property such as Enum.values[index]. It returns the Enum object.

Here is an example code

void main() {
  int index = WEEK.SUNDAY.index;
  print(index); // 6
  print(WEEK.values[index]); //WEEK.SUNDAY
}

Conclusion

Learned the following items with examples

  • Loop enum constants using for in and forEach loop
  • Get an index from an Enum, convert the index to Enum