Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 12 of 19 · 6 min read

Dart enums, records and pattern matching

Dart 3 notes with examples: enums and enhanced enums, records, destructuring, switch expressions, patterns with when guards, and sealed classes.

enum: a fixed set of choices

An enum lists every possible value of something that has a fixed set of options: order status, traffic-light colour, day of the week. The compiler then rejects any other value.

enum OrderStatus { placed, packed, shipped, delivered }

void main() {
  var s = OrderStatus.shipped;
  print(s);
  print(s.name);
  print(s.index);
  print(OrderStatus.values.length);
  print(s == OrderStatus.delivered);
}
OrderStatus.shipped
shipped
2
4
false
  • name is the value's name as text; index its position from 0.
  • OrderStatus.values lists all values, in order.
  • OrderStatus.values.byName('packed') turns text back into the enum value.

Enhanced enums: fields and methods

Since Dart 2.17 an enum can carry data and behaviour, like a small class:

enum Plan {
  free(0, 5),
  premium(199, 50),
  premiumPlus(499, 200);

  final int pricePerMonth;
  final int testsPerMonth;
  const Plan(this.pricePerMonth, this.testsPerMonth);

  bool get isPaid => pricePerMonth > 0;
}

void main() {
  for (var p in Plan.values) {
    print('${p.name}: Rs ${p.pricePerMonth}, ${p.testsPerMonth} tests, paid: ${p.isPaid}');
  }
}
free: Rs 0, 5 tests, paid: false
premium: Rs 199, 50 tests, paid: true
premiumPlus: Rs 499, 200 tests, paid: true

Every field must be final and the constructor const.

Records: several values without a class

A record (Dart 3) groups a few values into one. It is perfect for returning more than one value from a function.

(int, int) minMax(List<int> xs) {
  var lo = xs[0], hi = xs[0];
  for (var x in xs) {
    if (x < lo) lo = x;
    if (x > hi) hi = x;
  }
  return (lo, hi);
}

void main() {
  var r = minMax([40, 72, 15, 98]);
  print(r);
  print(r.$1);
  print(r.$2);

  var student = (name: 'Asha', marks: 88);   // named fields
  print(student.name);
  print(student);
}
(15, 98)
15
98
Asha
(marks: 88, name: Asha)

Positional fields are read as $1, $2, ...; named fields by name. When a record is printed, its named fields appear in alphabetical order. Records are compared by value: (1, 2) == (1, 2) is true.

Destructuring

A pattern on the left of = unpacks a value into variables:

(String, int) topper() => ('Meena', 97);

void main() {
  var (name, marks) = topper();
  print('$name $marks');

  var [first, second, ...rest] = [10, 20, 30, 40];
  print('$first $second $rest');

  var {'city': city, 'pin': pin} = {'city': 'Ranchi', 'pin': 834001};
  print('$city $pin');

  var a = 1, b = 2;
  (a, b) = (b, a);   // swap
  print('$a $b');
}
Meena 97
10 20 [30, 40]
Ranchi 834001
2 1

Patterns also work in for loops: for (var (name, marks) in results) ....

switch expressions and patterns

A switch expression returns a value. Each case is a pattern, followed by =>. _ matches anything. when adds a condition (a guard).

String grade(int marks) => switch (marks) {
      >= 90 => 'A+',
      >= 75 => 'A',
      >= 60 => 'B',
      >= 33 => 'C',
      _ => 'F',
    };

String describe(Object value) => switch (value) {
      int n when n < 0 => 'negative int',
      int n => 'int $n',
      String s => 'text of length ${s.length}',
      (int x, int y) => 'point at $x, $y',
      [] => 'empty list',
      [var only] => 'list with one item: $only',
      _ => 'something else',
    };

void main() {
  print(grade(82));
  print(describe(-5));
  print(describe(7));
  print(describe('Dart'));
  print(describe((3, 4)));
  print(describe([]));
  print(describe(['x']));
  print(describe(2.5));
}
A
negative int
int 7
text of length 4
point at 3, 4
empty list
list with one item: x
something else

Cases are tried from top to bottom; the first match wins.

Sealed classes and exhaustive switch

A sealed class can only be extended in its own file, so the compiler knows every subclass. A switch over it must handle them all; forget one and you get a compile-time error, not a bug.

sealed class Result {}

class Success extends Result {
  final String data;
  Success(this.data);
}

class Failure extends Result {
  final String error;
  Failure(this.error);
}

class Loading extends Result {}

String show(Result r) => switch (r) {
      Success(:final data) => 'Got: $data',
      Failure(:final error) => 'Error: $error',
      Loading() => 'Loading...',
    };

void main() {
  print(show(Success('5 students')));
  print(show(Failure('no internet')));
  print(show(Loading()));
}
Got: 5 students
Error: no internet
Loading...

Success(:final data) is an object pattern: it checks the type and pulls out the data field. Switching over an enum is exhaustive in the same way.

Common mistakes

  • Using strings such as 'shipped' for statuses; a typo compiles. Use an enum.
  • Forgetting _ in a switch expression on an open type such as int: the switch is not exhaustive.
  • Putting a broad pattern (int n) above a narrower one (int n when n < 0): the second never runs.
  • Reading record fields as r.1; it is r.$1.
  • Returning a record for many related values that deserve a named class.

Key points

  • Enums list a fixed set of values; enhanced enums add fields and methods.
  • Records (a, b) and (name: a) bundle values; read with $1 or the field name.
  • Patterns destructure records, lists and maps into variables.
  • switch expressions return a value; cases can use relational patterns, types, when guards and _.
  • sealed classes make switches exhaustive, so missing cases are compile-time errors.

Practice questions

1. Declare enum Light { red, yellow, green } and print the action for each with a switch expression.
enum Light { red, yellow, green }

String action(Light l) => switch (l) {
      Light.red => 'Stop',
      Light.yellow => 'Wait',
      Light.green => 'Go',
    };

void main() {
  for (var l in Light.values) {
    print('${l.name}: ${action(l)}');
  }
}
2. Write a function that returns the total and average of a list as a record.
(int, double) stats(List<int> xs) {
  var total = xs.reduce((a, b) => a + b);
  return (total, total / xs.length);
}

void main() {
  var (total, avg) = stats([10, 20, 30]);
  print('$total $avg');   // 60 20.0
}
3. What is printed? var (a, b) = (5, 'five'); print(b);

five. The record is destructured into a = 5 and b = 'five'.

4. Why does a switch over a sealed class not need _?

The compiler knows every subclass, so a switch that handles all of them is already exhaustive. If one is missing, it reports a compile-time error.

5. Use a switch expression with when to label a temperature: below 15 cold, 15 to 30 pleasant, above 30 hot.
String label(int t) => switch (t) {
      int x when x < 15 => 'cold',
      int x when x <= 30 => 'pleasant',
      _ => 'hot',
    };

void main() {
  print(label(22));   // pleasant
}