Control Flow
Switch Expression
Pattern Arms
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);
}
code ← 2
1void main() {2 Object code = 2;3 var label = switch (code) {values this step2codematched arm ← 2 => 'two'
2Object code = 2;3var label = switch (code) {4 1 => 'one',values this step2 => 'two'matched arm2codelabel ← two
41 => 'one',52 => 'two',6_ => 'many',values this steptwolabelprint(label);
7 };8 print(label);9}outputtwovalues this steptwolabel
Choose the Label
codestarts as2.- The switch expression checks each arm.
- The
2 => 'two'arm matches. - 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