๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Enums

An enum is a type with a fixed list of named values. Each value in the list is one allowed choice.

Printing an enum value

Level lists two values, low and high. The variable holds Level.high, and the print shows both names.

enum Level { low, high }

void main() {
  var level = Level.high;
  print(level);
}

Changing an enum value

The variable starts at Level.low and then takes Level.high. The two prints show the change.

enum Level { low, high }

void main() {
  var level = Level.low;
  print(level);
  level = Level.high;
  print(level);
}

A switch over enum values

The switch tests level against each enum value. The low case matches, so only its line prints.

enum Level { low, high }

void main() {
  var level = Level.low;
  switch (level) {
    case Level.low:
      print('Low level');
    case Level.high:
      print('High level');
  }
}

Comparing an enum value

The if test compares level with Level.high. The values match, so the print runs.

enum Level { low, high }

void main() {
  var level = Level.high;
  if (level == Level.high) {
    print('At the top');
  }
}

Example

enum Level { low, high }

void main() {
  var level = Level.high;
  print(level);
  switch (level) {
    case Level.low:
      print('Low level');
    case Level.high:
      print('High level');
  }
}

Key points

  • enum: a keyword that starts an enum definition.
  • The values of an enum sit inside braces, split by commas.
  • Write a value with the enum name, a dot, and the value name.
  • Printing an enum value shows the enum name and the value name.
  • A switch can test an enum value one case at a time.

In this example, level holds Level.high. The first print shows Level.high. The switch tests level, and the high case matches. The switch prints High level.

Note

An enum variable can only hold one of the values in its list.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does printing Level.high show?