Sobes.tech
Junior

How to implement branching using the switch statement in Dart?

sobes.tech AI

Answer from AI

Branching with the switch operator in Dart is performed as follows:

void main() {
  var color = 'red';

  switch (color) {
    case 'red':
      print('Selected color is red.');
      break; // Ends the switch block
    case 'blue':
      print('Selected color is blue.');
      break;
    case 'green':
      print('Selected color is green.');
      break;
    default: // Executes if no case matches
      print('Unknown color.');
  }
}

switch compares the value of the variable (in this case color) with the constants specified after case. When a match occurs, the code associated with that case is executed. The break keyword is necessary to exit the switch block after executing the corresponding case. If omitted, execution will continue to the next case (this is called "fallthrough"), which is usually undesirable. default is used to handle cases where none of the case options match.

It is important to remember that in Dart, switch can only use the following expression types in case:

  • int
  • Strings (String)
  • Compile-time constants (const) or final (final) variables of primitive types
  • Enums (enum)

You can also match by type using case (Type value):

void process(dynamic value) {
  switch (value) {
    case String s:
      print('Value is a string: $s');
      break;
    case int i when i > 0: // Using guard clause with when
      print('Value is a positive integer: $i');
      break;
    case List _: // Matching with List type without binding to a variable
      print('Value is a list');
      break;
    default:
      print('Value is of another type');
  }
}

void main() {
  process('hello');
  process(10);
  process([1, 2, 3]);
  process(3.14);
}

In Dart 3.0, new pattern matching capabilities have been introduced, expanding switch expressions:

var number = 1;
var text = switch (number) {
  1 => 'one',
  2 => 'two',
  _ => 'other' // Equivalent to default
};
print(text); // Outputs: one

Here, switch is used as an expression that returns a value. The _ operator acts as a wildcard, matching any value.