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

Dart Enhanced Enums

An enhanced enum value carries its own data. Each value is built by a const constructor on the enum itself.

Values carrying a field

Each planet passes its position to the const constructor. The loop prints the name and the stored field for every value.

enum Planet {
  mercury(1),
  venus(2),
  earth(3),
  mars(4);

  const Planet(this.order);

  final int order;

  bool get isInner => order <= 2;

  String describe() {
    return '$name orbits at position $order';
  }
}

void main() {
  for (final p in Planet.values) {
    print('${p.name} ${p.order}');
  }
}

A getter on the enum

The isInner getter reads the stored order field. The first two planets count as inner and the rest do not.

enum Planet {
  mercury(1),
  venus(2),
  earth(3),
  mars(4);

  const Planet(this.order);

  final int order;

  bool get isInner => order <= 2;

  String describe() {
    return '$name orbits at position $order';
  }
}

void main() {
  print(Planet.mercury.isInner);
  print(Planet.venus.isInner);
  print(Planet.earth.isInner);
  print(Planet.mars.isInner);
}

A method on the enum

The describe method builds a sentence from the name and the field. One value is enough to call it.

enum Planet {
  mercury(1),
  venus(2),
  earth(3),
  mars(4);

  const Planet(this.order);

  final int order;

  bool get isInner => order <= 2;

  String describe() {
    return '$name orbits at position $order';
  }
}

void main() {
  final home = Planet.earth;
  print(home.describe());
  print(home == Planet.earth);
}

Example

enum Planet {
  mercury(1),
  venus(2),
  earth(3),
  mars(4);

  const Planet(this.order);

  final int order;

  bool get isInner => order <= 2;

  String describe() {
    return '$name orbits at position $order';
  }
}

void main() {
  for (final p in Planet.values) {
    print(p.describe());
  }
  print(Planet.earth.isInner);
}

Key points

  • Values can pass arguments to a const constructor on the enum.
  • Fields on the enum store one value per enum entry.
  • An enum can declare getters and methods like a class.
  • The constructor of an enum must be const.
  • The values list still holds every entry in declaration order.
  • Each value keeps its name, readable through the name property.

In this example, the loop walks the values list in declaration order and calls describe on each planet. Each call reads the name and the order field stored on that value. The last print reads the isInner getter on earth, which is false because its order is 3.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

How does an enhanced enum value get its field data?