Enumerated types

Enumerated types, often called enumerations or enums,are a special kind of class used to representa fixed number of constant values.

Using enums

Declare an enumerated type using the enum keyword:

1. enum Color { red, green, blue }

Each value in an enum has an index getter,which returns the zero-based position of the value in the enum declaration.For example, the first value has index 0,and the second value has index 1.

1. assert(Color.red.index == 0);
2. assert(Color.green.index == 1);
3. assert(Color.blue.index == 2);

To get a list of all of the values in the enum,use the enum’s values constant.

1. List<Color> colors = Color.values;
2. assert(colors[2] == Color.blue);

You can use enums in switch statements, andyou’ll get a warning if you don’t handle all of the enum’s values:

1. var aColor = Color.blue;

3. switch (aColor) {
4. case Color.red:
5. print('Red as roses!');
6. break;
7. case Color.green:
8. print('Green as grass!');
9. break;
10. default: // Without this, you see a WARNING.
11. print(aColor); // 'Color.blue'
12. }

Enumerated types have the following limits:

  • You can’t subclass, mix in, or implement an enum.
  • You can’t explicitly instantiate an enum.

For more information, see the Dart language specification.