CodeBlanks Logo Icon CodeBlanks

Pattern matching

Learn Dart 3 switch expressions and pattern matching.

Pattern matching

The switch expression, introduced in Dart 3, is the expression (value-producing) form of switch. The result can be assigned to a variable: var name = switch (day) { "Mon" => "Monday", _ => "Unknown" };.

Two key differences: (1) instead of case and a colon, the => arrow is used; (2) break is not needed because each arm ends automatically. The _ underscore is the wildcard pattern meaning "everything else"; it replaces default.

The wildcard pattern _

In a switch expression the _ underscore is the wildcard pattern meaning "all other values". It replaces default and is usually written last. In a switch expression the _ arm is required; otherwise some values would produce no result and a compile error occurs.

Example: var t = switch (n) { 1 => "one", 2 => "two", _ => "other" };. Here if n is neither 1 nor 2 the _ arm runs and returns "other".

Practice Day type with switch expression

Declare a String variable day with the value "Fri". Declare a variable desc and assign it to a switch (day) expression: use arms "Fri" => "Almost weekend" and _ => "Midweek". Then print desc with print(desc);. The output on a single line must be Almost weekend.

Starter code

main.dart
// Declare day, assign desc with a switch expression and print it

Sample solution

main.dart
String day = "Fri";
var desc = switch (day) {
  "Fri" => "Almost weekend",
  _ => "Midweek",
};
print(desc);

Expected output

Almost weekend

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which sign separates arms in a switch expression?

main.dart
var x = switch (n) {
  1 => "one",
  _ => "other",
};
  • case ... :
  • => Correct answer
  • :
  • ->

Explanation: Each arm in a switch expression produces a value with the => arrow.

2 Match each part to its job

Term Meaning
switch (x) { Value to check
=> Result arrow
_ Wildcard (other)
var y = switch Assign result to variable

3 Write the switch expression arm

Question
String day = "Fri";
var desc = switch (day) {
  ____
  _ => "Midweek",
};
print(desc);
Answer
String day = "Fri";
var desc = switch (day) {
  "Fri" => "Almost weekend",
  _ => "Midweek",
};
print(desc);

Explanation: The => arrow produces a value; the line ends with a comma.

All lessons in Beginner