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

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.