Dart: Enums

Carlos Costa

In brief, enums are a way of giving more semantic meaning to a set of values. They are a way of creating a new type in Dart.

Example:

enum Status {
  none,
  running,
  stopped,
  paused,
}

Enums are a way of creating a new type in Dart. In the example above, we created a new type called Status that can have the values none, running, stopped and paused.

To get a value from an enum, we can use the values property:

Status.none;
// Status.none
Status.values;
// [Status.none, Status.running, Status.stopped, Status.paused]

You also can get the index of an enum value:

Status.none.index;
// 0
Status.running.index;
// 1
Status.stopped.index;
// 2
Status.paused.index;
// 3

And the name as String:

Status.none.name;
// none
Status.running.name;
// running
Status.stopped.name;
// stopped
Status.paused.name;
// paused

Enums with custom names


enum Colors {
  red("RED"),
  green("GREEN"),
  blue("BLUE");

  final String name;
  const Colors(this.name);
}

void main(){
  for (var color in Colors.values) {
    print(color.name);
  }
  // RED, GREEN, BLUE
}

Here we have a enum called Colors with the values red, green and blue. Each value has a custom name property.

Enum and extension


We can modify an enum after it’s created using extension.

enum Colors {
  red,
  green,
  blue,
}

extension ColorsExtension on Colors {
  String get name {
    switch (this) {
      case Colors.red:
        return "RED";
      case Colors.green:
        return "GREEN";
      case Colors.blue:
        return "BLUE";
    }
  }
}

void main(){
  for (var color in Colors.values) {
    print(color.name);
  }
  // RED, GREEN, BLUE
}

References