CodeBlanks Logo Icon CodeBlanks

Enhanced enums

Learn Dart 3 enhanced enums.

Enhanced enum

Dart 3 introduced enhanced enum. In addition to constants you can add fields, constructors and methods. So each constant carries its own data. A classic enum holds only a name; an enhanced enum holds name plus value.

Example: enum Heat { low(10), medium(25), high(40); final int degrees; const Heat(this.degrees); }. Each constant gets a degrees field; Heat.medium.degrees gives 25. The constructor must be const; otherwise you get a compile error. This lets you treat constants like real types.

Fields and methods

To add fields to an enhanced enum, place a semicolon after the constant list and then the field definitions. enum Distance { near(5), far(50); final int km; const Distance(this.km); int get meters => km * 1000; }. Here meters is a computed getter.

Each constant can access these fields and methods: Distance.far.meters gives 50000. So the enum is not just a label but a type carrying real behavior. The conditions are: the constructor must be const, all fields must be final, and a semicolon after the constant list is required.

Practice Your turn: enum with a degrees field

Define an enhanced enum Heat with constants low(10), medium(25), high(40). Add a final int degrees field and a const Heat(this.degrees) constructor. In main print Heat.medium.degrees.

Starter code

main.dart
void main() {
  // Define the Heat enhanced enum
  // Print a constant's degrees field
}

Sample solution

main.dart
enum Heat { low(10), medium(25), high(40); final int degrees; const Heat(this.degrees); }

void main() {
  print(Heat.medium.degrees);
}

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an enhanced enum support?

  • Only methods Correct answer
  • Fields and a constructor
  • Only a name
  • Only an index

Explanation: An enhanced enum supports fields and a constructor.

2 The const constructor

Question
enum Heat { low(10), medium(25), high(40); final int degrees; ____ Heat(this.degrees); }
Answer
enum Heat { low(10), medium(25), high(40); final int degrees; const Heat(this.degrees); }

Explanation: An enhanced enum constructor must be const.

3 Match enhanced enum conditions

Term Meaning
const constructor is required
final field immutable data
semicolon after the constant list
method computed behavior

All lessons in Beginner