Enum values
- Dart course
- Beginner
- Lesson 95/116
- 4 min
Learn to access enum members.
Accessing enum values
You access all constants of a defined enum with .values. It is a list of constants in their writing order. Color.values gives you [Color.red, Color.green, Color.blue]. You can loop over it, take the first or the last element.
Each constant has an .index property giving its position in the definition; the first constant is 0. .name returns the constant's name as a string. Color.green.name gives "green". These properties are useful for listing enums, building menus and logging.
The index property
The position of a constant in the definition is given by .index. The first constant is 0, the next ones increase by one. Color.red.index gives 0, Color.blue.index gives 2. Handy to show which row a constant is on in a menu.
.name returns the constant's name as a string; Color.green.name gives "green". They can be used together: a log line can carry both the index and the name. Comparing with .name strings is riskier than using Color.green directly; a typo is caught at compile time with the constant.
Practice Your turn: list constants
Define an enum Day with constants monday, tuesday, wednesday. In main loop over Day.values with a for and print each .name.
Starter code
void main() {
// Define Day enum: monday, tuesday, wednesday
// Loop over all constants
// Print .name
}Sample solution
enum Day { monday, tuesday, wednesday }
void main() {
for (final d in Day.values) {
print(d.name);
}
}Expected output
monday tuesday wednesday
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The .values property
final list = Color.____;
final list = Color.values;
Explanation: .values gives all constants as a list.
2 Match enum properties
| Term | Meaning |
|---|---|
.values |
list of all constants |
.index |
position number |
.name |
constant name as string |
Color.green |
a single constant |
3 What does Color.values return?
final all = Color.values;- a single Color
- a number
- a string
- a list of Color (List<Color>) Correct answer
Explanation: .values is the list of all constants.