DMarlon Studio

Lesson 7 · 7 of 20

switch and switch expressions · Dart

Choose between many cases with switch in Dart 3: the classic statement, the new switch expression with =>, patterns such as || and >=, and when guards.

Dart · switch and switch expressions in DMarlon Studio: the example's code and its output in the terminal

The `switch` statement compares a value against each case and runs the one that matches. In Dart 3 you do not need break: once a case finishes, the switch is over. case 'Sat' || 'Sun': groups two values in one case, and `default` catches everything else.

The `switch` expression is new in Dart 3: instead of running statements, it returns a value, stored here in season. Each case is pattern => value, separated by commas, and `_` is the wildcard that matches anything. With it, picking the season of a month takes just a few lines.

Cases are patterns, and a pattern can compare: >= 90 => 'A' matches any number of 90 or more. Since Dart tries them in order, the score 84 misses >= 90 but matches >= 70, and the whole expression fits on one line.

Patterns combine with `&&`: >= 0 && <= 50 is a range. And `when` adds an extra condition that can look at other variables: _ when school only matches when school is true. That is why 65 km/h gives too fast near a school.

A switch expression must cover every possible case; leave out the _ and Dart complains before running. It is the clearest way to turn one value into another.

Code · main.dart

void main() {  String day = 'Sat'; // switch runs the case that matches  switch (day) {    case 'Sat' || 'Sun':      print('$day: weekend, the shop opens at 10.');    default:      print('$day: open from 9 to 8.');  }  // switch expression: gives back a value. _ catches the rest.  int month = 4;  String season = switch (month) {    12 || 1 || 2 => 'winter',    3 || 4 || 5 => 'spring',    6 || 7 || 8 => 'summer',    _ => 'autumn',  };  print('Month $month is in $season.');  // Patterns can also compare: >= 90, >= 70...  int score = 84;  String grade = switch (score) { >= 90 => 'A', >= 70 => 'B', >= 50 => 'C', _ => 'F' };  print('Score $score: grade $grade');  // && joins two patterns; "when" adds an extra condition.  int speed = 65;  bool school = true;  String note = switch (speed) {    >= 0 && <= 50 => 'within the limit',    _ when school => 'too fast near a school',    _ => 'slow down',  };  print('$speed km/h: $note');}

Output · dart run main.dart

Sat: weekend, the shop opens at 10.
Month 4 is in spring.
Score 84: grade B
65 km/h: too fast near a school

Key points

  • In Dart 3, case does not need break.
  • switch (x) { pattern => value, ... } returns a value.
  • _ matches anything.
  • ||, >= and && build patterns.
  • when adds a condition to a case.

Exercise

Using a switch expression, turn a day variable from 1 to 7 into the English name of the day, and use _ to give invalid day for any other number.