๐ŸŽ“ A1Learner
๐Ÿ”
0 of 24 lessons completed

Dart Switch Expressions

A switch expression matches a value against patterns and produces a result. Each arm pairs a pattern with the value that arm gives back.

Grade bands with relational patterns

Each relational pattern matches the scores from its band upward. The first matching arm gives the grade, and the wildcard covers the lowest scores.

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

void main() {
  print(grade(95));
  print(grade(85));
  print(grade(72));
  print(grade(40));
}

Matching either value with a logical-or pattern

The first arm matches count 1 or count 2 with one pattern. The wildcard arm gives the result for the second value, 5.

void main() {
  var count = 2;
  var word = switch (count) {
    1 || 2 => 'tiny',
    3 || 4 => 'small',
    _ => 'big',
  };
  print(word);
  count = 5;
  var label = switch (count) {
    1 || 2 => 'tiny',
    3 || 4 => 'small',
    _ => 'big',
  };
  print(label);
}

Binding the value with a variable pattern

The first two arms match fixed day numbers. The variable pattern int d binds any other day number, and its arm uses d in the result.

void main() {
  var day = 3;
  var name = switch (day) {
    1 => 'Monday',
    2 => 'Tuesday',
    int d => 'day $d',
  };
  print(name);
  day = 1;
  var first = switch (day) {
    1 => 'Monday',
    2 => 'Tuesday',
    int d => 'day $d',
  };
  print(first);
}

Example

String classify(int size) {
  return switch (size) {
    >= 100 => 'huge',
    1 || 2 => 'tiny',
    _ => 'medium',
  };
}

void main() {
  print(classify(150));
  print(classify(1));
  print(classify(50));
}

Key points

  • A switch expression produces a value. The value can be returned, assigned, or printed.
  • Each arm has the form pattern => result, and the arms are separated by commas.
  • A relational pattern such as >= 90 matches a whole range of values.
  • A logical-or pattern such as 1 || 2 matches either of the two values.
  • A variable pattern binds the matched value to a name the arm can use.
  • A wildcard arm _ covers every value the earlier arms miss, so the switch can always produce a result.

In this example, classify mixes one relational arm, one logical-or arm, and one wildcard arm. The value 150 matches the relational arm and prints huge. The value 1 matches the or arm and prints tiny, and 50 falls to the wildcard and prints medium.

Note

Only the matching arm runs. No arm falls through into the next one.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does the arm 1 || 2 => 'tiny' match?