Dart 3 introduces switch expressions with patterns. Each arm yields a value, and _ is the wildcard.

Program

Play the program to map an integer code to a label.

switch_pattern.dart
Replay: real traced execution (multi-file project)
void main() {
  Object code = 2;
  var label = switch (code) {
    1 => 'one',
    2 => 'two',
    _ => 'many',
  };
  print(label);
}
  1. code ← 2

    1void main() {2  Object code = 2;3  var label = switch (code) {
    values this step2code
  2. matched arm ← 2 => 'two'

    2Object code = 2;3var label = switch (code) {4  1 => 'one',
    values this step2 => 'two'matched arm2code
  3. label ← two

    41 => 'one',52 => 'two',6_ => 'many',
    values this steptwolabel
  4. print(label);

    7  };8  print(label);9}
    outputtwo
    values this steptwolabel

Choose the Label

  1. code starts as 2.
  2. The switch expression checks each arm.
  3. The 2 => 'two' arm matches.
  4. The program prints two. | Code | Matching arm | Label | | --- | --- | --- | | 2 | 2 => | two |
switch expression `switch (x) { ... }` evaluates to a value.
pattern arm `1 =>`, `2 =>`, etc. match constant patterns.
wildcard `_` matches anything not handled above.

Exercise: switch_pattern.dart

Use a switch expression to map code 2 to the label two and print it