Dart Enum

enum is a special class in Dart that contains a list of constants. enum keyword is used to define enumerations.

Define

To define an enum Color with three values red, green, and blue, use enum keyword as shown in the following.

</>
Copy
enum Color {
  red,
  green,
  blue
}

Access

Dot operator is used to access each of the constants in enum.

</>
Copy
Color.red

Index of Constants in Enum

Each constant of the Enum is assigned an index (starting with 0). This index can be accessed using index getter on the enum value.

</>
Copy
Color.red.index //returns 0

Examples

In the following example, we define an enum Color with three values red, green, and blue. Then we shall use these enum values as items of a list.

main.dart

</>
Copy
enum Color { red, green, blue }

void main() {
  List<Color> colors = [];
  colors.add(Color.red);
  colors.add(Color.blue);
  print(colors);
}

Output

[Color.red, Color.blue]

In the following example, we print the index of enum values using index getter.

main.dart

</>
Copy
enum Color { red, green, blue }

void main() {
  print(Color.red.index);
  print(Color.green.index);
  print(Color.blue.index);
}

Output

0
1
2

Conclusion

In this Dart Tutorial, we learned the concept of Enumerations in Dart, and how to work with them, with the help of examples.