Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 61 ยท Classes and Object-Oriented Dart

Enums and Enhanced Enums

Learn Dart enums: declaring values, the values list, name and index, switch exhaustiveness and enhanced enums with fields, constructors, methods and interfaces.

Some values come from a small, fixed set: the days of the week, the state of a download, the suit of a playing card. Storing them as strings or magic numbers invites typos and invalid values. An enum (short for enumeration) declares the whole set once, gives each member a name, and lets the compiler check that you only use members that exist.

Dart enums start out simple, but since Dart 2.17 they can also carry fields, constructors and methods, and they can implement interfaces. These are called enhanced enums, and they replace many small classes. The Dart code below is read-only, and the runnable examples are TypeScript stand-ins that show the same ideas.

Declaring a simple enum

An enum is a list of names between braces:

DART
enum Status { pending, running, done, failed }

void main() {
  Status s = Status.running;
  print(s);          // Status.running
  print(s.name);     // running
  print(s.index);    // 1
}
TEXT
Status.running
running
1

Every enum value has two built-in properties. name is the identifier as a string, and index is its zero-based position in the declaration. Printing a value shows Status.running, so use .name when you need only the member name, for example in a log line or a JSON field.

Enum values are constants and there is exactly one object per member, so you compare them with == (which is identity here) and never create new ones. You cannot instantiate an enum with Status() or extend it.

The values list

Every enum has a static values list that holds all members in declaration order. It is how you loop over the set, build a dropdown or count the options:

DART
enum Size { small, medium, large }

void main() {
  for (final size in Size.values) {
    print('${size.index}: ${size.name}');
  }
  print(Size.values.length);   // 3
}

There is also a helper that turns a string back into a member. Size.values.byName('large') returns Size.large and throws an ArgumentError for an unknown name. When the input may be wrong, as it is with data from a file or a network request, use Size.values.asNameMap() (a Map<String, Size>) and check for null, or write a small where search.

Do not store index in a database or file if you might later reorder or insert members. The numbers shift. Names are safer to persist.

flowchart LR
    E["enum Size"] --> A["small<br/>index 0"]
    E --> B["medium<br/>index 1"]
    E --> C["large<br/>index 2"]
    V["Size.values"] -.-> E

An enum declares a fixed set of members; values lists them in order.

TypeScript A fixed set of values (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Switching over an enum

A switch over an enum is exhaustive: the compiler knows every member, so a switch expression must cover all of them, and you do not need a default. If you later add a member, every switch that forgets it becomes a compile error, which is exactly what you want.

DART
enum Status { pending, running, done, failed }

String label(Status s) => switch (s) {
      Status.pending => 'Waiting',
      Status.running => 'In progress',
      Status.done => 'Finished',
      Status.failed => 'Something went wrong',
    };

Avoid adding a default or _ => branch to an enum switch. It silences the very check that protects you when the enum grows. The switch lesson, switch Statements and Expressions, covers the syntax in detail.

Enhanced enums

An enhanced enum can have fields, a constructor, methods, getters, static members and implements or with clauses. The rules are strict so the set stays closed:

  • All fields must be final.
  • The constructor must be const.
  • The members come first, separated by commas, and end with a semicolon before any other declarations.
DART
enum Planet {
  mercury(radiusKm: 2440, moons: 0),
  earth(radiusKm: 6371, moons: 1),
  mars(radiusKm: 3390, moons: 2);

  const Planet({required this.radiusKm, required this.moons});

  final int radiusKm;
  final int moons;

  bool get hasMoons => moons > 0;

  String describe() => '$name: radius $radiusKm km, $moons moon(s)';
}

void main() {
  print(Planet.earth.describe());     // earth: radius 6371 km, 1 moon(s)
  print(Planet.mercury.hasMoons);     // false
}

Each member calls the constructor with its own arguments, so the data lives next to the name. This replaces the old pattern of a parallel Map<Planet, int> that you had to keep in sync by hand. Members may also implement behavior differently, either with a switch on this inside a method or through an interface.

DART
abstract interface class Describable {
  String describe();
}

enum Level implements Describable {
  low(1),
  high(3);

  const Level(this.weight);
  final int weight;

  @override
  String describe() => '$name with weight $weight';
}

An enum can implement interfaces and use mixins, but it cannot extend another class. If you need a hierarchy where each case holds different data, use a sealed class instead, which is covered in Class Modifiers: sealed, final, base.

TypeScript Members that carry data (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Limits of plain enums

A simple enum has a few limits you should know: you cannot add members after declaring it, you cannot extend or implement-and-instantiate it from outside, every constant is a single shared instance, and values have no data unless you use an enhanced enum. If you need open-ended sets of values, an ordinary class with static const instances, or a sealed class, is the better choice.

Generic enums and common patterns

Enums can be generic when they need to carry typed data, for example enum Handler<T> { ... }, though this is rare. More often you will use these small patterns:

  • Parsing: add a static method such as static Status? tryParse(String text) that returns a member or null.
  • Display text: add a getter, String get title => ..., instead of repeating a switch at every use.
  • Ordering: enums have no < operator. To sort by declaration order, compare indexes, for example list.sort(Enum.compareByIndex) or (a, b) => a.index.compareTo(b.index).
  • Collections: enums are fine as Map keys and Set members, and a Map<Status, int> is a simple way to count occurrences per member.

Because enum members are compile-time constants, you can use them in const contexts and in default parameter values, for example void log(String msg, {Level level = Level.low}).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Status.running.name return?

    name is the member identifier as a plain string. index is the number, and print shows Status.running.
  2. 2. Why is it good to leave out the default branch in a switch over an enum?

    Enum switches are exhaustive. Without a default branch, adding a member turns every incomplete switch into a compile error.
  3. 3. Which rule applies to fields of an enhanced enum?

    Enum members are constants, so their fields are final and the constructor is const.
  4. 4. How do you get all members of an enum in declaration order?

    Every enum has a static values list holding all its members in declaration order.
  5. 5. Which statement about enums is true?

    Enums can implement interfaces and use mixins, but they cannot extend classes, and the set of members is fixed. Persisting index is risky because reordering changes it.

Summary

  • An enum declares a closed set of named constants; name is the identifier and index is the position.
  • values lists all members, and values.byName converts a string back (throwing if it is unknown).
  • switch over an enum is exhaustive, so skip default and let the compiler find missing cases.
  • Enhanced enums add final fields, a const constructor, methods, getters and interfaces.
  • Prefer persisting names over indexes.

Next, add behavior to types you do not own with Extension Methods and Extension Types.