Skip to content
AgileLogics
6 min read

switch Statements and Expressions

Prerequisites: Conditionals

switch compares a value against several patterns and runs the first one that matches. Dart 3's switch is powerful — it can match ranges, types, and the structure of data.

switch statement

void main() {
  const day = 'Saturday';

  switch (day) {
    case 'Saturday' || 'Sunday':
      print('Weekend!');
    case 'Friday':
      print('Almost weekend');
    default:
      print('Weekday');
  }
}
Weekend!
  • || inside a case matches either value.
  • Only the matching case runs — there's no "fall-through" into the next case, and no break needed.

switch expressions

A switch expression produces a value. Each case is pattern => result, separated by commas, and _ matches anything else:

void main() {
  const score = 84;

  final grade = switch (score) {
    >= 90 => 'A',
    >= 80 => 'B',
    >= 70 => 'C',
    _ => 'F',
  };
  print(grade);

  const temperature = -3;
  final feeling = switch (temperature) {
    < 0 => 'freezing',
    >= 0 && < 15 => 'cold',
    >= 15 && < 25 => 'pleasant',
    _ => 'hot',
  };
  print(feeling);
}
B
freezing

>= 90 is a relational pattern; && and || combine patterns. Switch expressions must be exhaustive — every possible value has to be handled, which is why _ is needed here.

Matching types

String describe(Object value) => switch (value) {
      int n when n < 0 => 'a negative number',
      int() => 'a whole number',
      String s => 'text of length ${s.length}',
      _ => 'something else',
    };

void main() {
  print(describe(-4));
  print(describe(7));
  print(describe('hi'));
  print(describe(2.5));
}
a negative number
a whole number
text of length 2
something else
  • String s matches a String and binds it to s, already typed as a String.
  • when adds an extra condition (a guard).

Level 2 goes further with records, sealed classes, and destructuring.

Practice

Given a month from 1 to 12, use a switch expression to produce the season (Northern Hemisphere): 12, 1, 2 → winter; 3–5 → spring; 6–8 → summer; 9–11 → autumn.

Show solution
void main() {
  const month = 7;

  final season = switch (month) {
    12 || 1 || 2 => 'winter',
    >= 3 && <= 5 => 'spring',
    >= 6 && <= 8 => 'summer',
    >= 9 && <= 11 => 'autumn',
    _ => 'invalid month',
  };
  print(season);
}
summer