Enumerated Types #2

Learn to write extensions and iterate over Enums.

We'll cover the following

In the last lesson, we learned how to use switch blocks for Enums. In this lesson, you will learn to iterate over members of Weather enumeration.

Iterating

Let’s revisit the Enum Weather:

enum Weather {
  sunny,
  cloudy,
  rainy,
}

The members of the Enums can be listed using Weather.values. The Weather.values returns List<Weather> type. As seen below, this list can be iterated over to print all members of the Weather enumerated type.

Weather.values.forEach((w) => print(w));

Output: Iterating over Weather.values, and printing enum members.

Weather.sunny
Weather.cloudy
Weather.rainy

Another reason to use Enums over constants is that constants require you to create a list to store all values and then iterate over that list.

Get hands-on with 1200+ tech skills courses.