TExcelTAD
Home › Dart › Dart Switch & Patterns

Dart Switch & Patterns

switch picks one branch out of many by comparing a value against a series of case clauses. In Dart 3 the switch statement became far more powerful: cases are patterns, so they can test types, ranges, list shapes and more — not just constants.

A basic switch statement

dart · try it yourself
void describeDay(String day) {
  switch (day) {
    case 'Sat':
    case 'Sun':
      print('$day: weekend');
    case 'Fri':
      print('$day: almost weekend');
    default:
      print('$day: work day');
  }
}

void main() {
  for (final d in ['Mon', 'Fri', 'Sun']) {
    describeDay(d);
  }
}
Mon: work day
Fri: almost weekend
Sun: weekend

Things to notice:

  • No break needed. Since Dart 3, a non-empty case doesn't fall through to the next one — it simply ends.
  • Empty cases share a body. case 'Sat': has no statements, so it falls into case 'Sun':.
  • default (or the wildcard case _:) catches anything not matched.

Logical-or patterns

Instead of stacking empty cases, combine alternatives with || in one case:

dart · try it yourself
String kind(String ch) {
  switch (ch) {
    case 'a' || 'e' || 'i' || 'o' || 'u':
      return 'vowel';
    case ' ':
      return 'space';
    default:
      return 'consonant';
  }
}

void main() {
  print('Dart is'.split('').map(kind).toList());
}
[consonant, vowel, consonant, consonant, space, vowel, consonant]

Note: Strings are case-sensitive — 'D' isn't 'd', so it falls to default, which is the right answer anyway.

Relational and type patterns

Cases can compare with <, >=, etc., and can test types while binding a variable:

dart · try it yourself
String classify(Object value) {
  switch (value) {
    case int n when n < 0:
      return 'negative int $n';
    case 0:
      return 'zero';
    case int() && >= 1 && <= 9:
      return 'single digit';
    case int():
      return 'large int';
    case double d:
      return 'double ${d.toStringAsFixed(1)}';
    case String s when s.isEmpty:
      return 'empty string';
    case String s:
      return 'string "$s"';
    default:
      return 'something else';
  }
}

void main() {
  for (final v in [-4, 0, 7, 42, 2.75, '', 'hey', true]) {
    print(classify(v));
  }
}
negative int -4
zero
single digit
large int
double 2.8
empty string
string "hey"
something else
Pattern Matches
0, 'x', null A constant (compared with ==)
int() && >= 1 && <= 9 An int that is also between 1 and 9 (relational patterns joined with &&)
int() Any int (an object pattern with no fields)
double d Any double, bound to d
_ Anything (wildcard)
case … when cond A pattern plus a guard

Cases are tried top to bottom; the first match wins. That's why case 0: is before case int():.

Note: A relational pattern such as >= 1 calls the >= operator on the value, so the value's type must have that operator. Here value is an Object, so we first narrow it with int() && …. When switching on an int directly, a bare case >= 1 && <= 9: works.

Destructuring in cases

Patterns can look inside lists, maps and records:

dart · try it yourself
String describeCommand(List<String> words) {
  switch (words) {
    case []:
      return 'no command';
    case ['help']:
      return 'showing help';
    case ['go', var direction]:
      return 'moving $direction';
    case ['take', var item, ...var rest]:
      return 'taking $item${rest.isEmpty ? '' : ' (ignoring ${rest.join(' ')})'}';
    default:
      return 'unknown: ${words.join(' ')}';
  }
}

void main() {
  for (final line in ['', 'help', 'go north', 'take lamp now please', 'dance']) {
    final words = line.isEmpty ? <String>[] : line.split(' ');
    print(describeCommand(words));
  }
}
no command
showing help
moving north
taking lamp (ignoring now please)
unknown: dance

Switch on enums

Switching over an enum lets the compiler check that every value is handled. Enums, bool and sealed types are always-exhaustive: if a switch on them forgets a value and has no default, it's a compile error. Add a fourth value to Signal below and run it to see:

dart · try it yourself
enum Signal { red, amber, green }

void main() {
  for (final s in Signal.values) {
    switch (s) {
      case Signal.red:
        print('stop');
      case Signal.amber:
        print('get ready');
      case Signal.green:
        print('go');
    }
  }
}
stop
get ready
go

Dart also has switch expressions, which produce a value: final msg = switch (s) { Signal.red => 'stop', … };. They're covered with exhaustiveness checking in Switch Expressions.

Test yourself

In Dart 3, what happens at the end of a non-empty case body without break?

  1. It falls through to the next case
  2. Compile error
  3. The switch ends
  4. The default case runs

When switching on an int, which case matches any value from 1 to 9?

  1. case 1..9:
  2. case >= 1 && <= 9:
  3. case 1 to 9:
  4. case [1, 9]:

What does case ['go', var direction]: match?

  1. Any list containing 'go'
  2. A two-element list whose first element is 'go'
  3. A string starting with 'go'
  4. A map with key 'go'