On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Why Not Just Strings?
  4. 2. Declaring and Using an Enum
  5. 3. Looping Over All Values
  6. 4. Enums and switch
  7. 5. Enums With Data (Enhanced Enums)
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 047: Enums

DayExtra Topics
Lecture047 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

The days of the week, the status of an order, the size of a coffee: each has a fixed list of choices. An enum (short for enumeration) names those choices, so a typo like 'shiped' can never sneak into your program.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lecture 019 (switch) and lectures 030–031 (classes and constructors).


Learning Objectives

  • Declare an enum and use its values
  • Read an enum value's name and index
  • Loop over all values with values
  • Use an enum in a switch, and let Dart check that every case is covered
  • Give enum values their own data (enhanced enums)

1. Why Not Just Strings?

dart
var status = 'shiped';   // typo: nobody notices until something breaks

With an enum, only the real choices exist, and a typo is a compile error.

2. Declaring and Using an Enum

dart
enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }

void main() {
  var today = Day.friday;
  print(today);              // Day.friday
  print(today.name);         // friday
  print(today.index);        // 4 (counting starts at 0)
  print(Day.values.length);  // 7
  print(Day.values.first);   // Day.monday
}
PropertyGives
value.namethe name as a String ('friday')
value.indexits position, starting at 0
EnumName.valuesa list of every value, in order
EnumName.values.byName('x')the value called 'x'

3. Looping Over All Values

dart
enum OrderStatus { pending, shipped, delivered, cancelled }

for (var s in OrderStatus.values) {
  print('${s.index}: ${s.name}');
}

Output

code
0: pending
1: shipped
2: delivered
3: cancelled

4. Enums and switch

dart
var status = OrderStatus.shipped;
switch (status) {
  case OrderStatus.pending:
    print('Waiting to be packed');
  case OrderStatus.shipped:
    print('On the way');
  case OrderStatus.delivered:
    print('Enjoy!');
  case OrderStatus.cancelled:
    print('Order cancelled');
}

Output: On the way

Dart checks that you handled every value. Add a new status later and forget it, and Dart points to the switch that needs updating.

5. Enums With Data (Enhanced Enums)

Each value can carry its own fields, and the enum can have methods:

dart
enum Planet {
  mercury(3.7),
  earth(9.8),
  jupiter(24.8);

  final double gravity;
  const Planet(this.gravity);

  double weightOf(double massKg) => massKg * gravity;
}

print(Planet.jupiter.gravity);                       // 24.8
print(Planet.earth.weightOf(60).toStringAsFixed(1)); // 588.0

The values end with ; when more code follows, the fields must be final, and the constructor must be const.


Code Examples

Example 1: A Drinks Menu

dart
enum Size {
  small(250, 150),
  medium(350, 200),
  large(500, 260);

  final int ml;
  final int price;
  const Size(this.ml, this.price);
}

enum Drink { tea, coffee, juice }

void main() {
  var drink = Drink.coffee;
  var size = Size.large;

  print('Order: ${size.name} ${drink.name}');
  print('Amount: ${size.ml} ml');
  print('Price: Rs ${size.price}');

  print('--- Menu ---');
  for (var s in Size.values) {
    print('${s.name.padRight(7)} ${s.ml} ml  Rs ${s.price}');
  }
}

Output

code
Order: large coffee
Amount: 500 ml
Price: Rs 260
--- Menu ---
small   250 ml  Rs 150
medium  350 ml  Rs 200
large   500 ml  Rs 260

padRight(7) adds spaces so the columns line up.


Common Beginner Mistakes

1. Missing a case in a switch

dart
enum Light { red, yellow, green }

switch (light) {
  case Light.red:
    print('Stop');
  case Light.green:
    print('Go');
}
code
Error: The type 'Light' is not exhaustively matched by the switch cases since it doesn't match 'Light.yellow'.
Try adding a default case or cases that match 'Light.yellow'.

2. Assigning a string to an enum variable

dart
Light light = 'red';
code
Error: A value of type 'String' can't be assigned to a variable of type 'Light'.

Write Light.red, or convert text with Light.values.byName('red').

3. Saving index and reordering later: if you store index (say, in a database) and then insert a new value in the middle, every saved number shifts. Store name instead.

4. Forgetting ; before fields in an enhanced enum: the list of values must end with ; when fields or methods follow.


Practice Questions

  1. Declare an enum Season with four seasons.
  2. What does Season.values.length give?
  3. What is Season.summer.name?
  4. Why is OrderStatus.shipped safer than the string 'shipped'?
  5. What happens if a switch over Season handles only three seasons and has no default?

Practice Answers

  1. enum Season { spring, summer, autumn, winter }
  2. 4
  3. 'summer'
  4. A typo in an enum value is a compile error; a typo in a string goes unnoticed.
  5. Dart reports a compile error: the switch isn't exhaustive.

Key Takeaways

  • An enum is a fixed set of named values: enum Day { monday, ... }.
  • Use .name, .index, .values and .values.byName().
  • A switch on an enum must cover every value; Dart checks.
  • Enhanced enums give each value its own data and methods.
  • Prefer enums over magic strings for fixed choices.