Switch Statements
Matching a value against multiple cases with switch — and the safer, more expressive switch expression form.
읽는 데 2분
A switch statement compares one value against several possible matches, which reads more clearly than a long chain of else if when you're checking the same variable against many exact values.
Basic switch statement
String day = 'Tuesday';
switch (day) {
case 'Monday':
print('Start of the work week');
break;
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
print('Midweek');
break;
case 'Friday':
print('Almost the weekend');
break;
default:
print('Weekend');
}Two things to notice: break is required at the end of each case with a body (Dart won't silently "fall through" to the next case the way some languages do, and the analyzer flags a missing break as an error, not just a warning). And stacking case 'Tuesday': directly above case 'Wednesday': with no code between them is how you group multiple values under one shared block.
switch expressions
Modern Dart also has a switch expression — it evaluates to a value directly, rather than running statements, and uses => instead of case:/break:
String describe(int score) {
return switch (score) {
>= 90 => 'A',
>= 80 => 'B',
>= 70 => 'C',
_ => 'F',
};
}
print(describe(85)); // BThis is usually the better choice when every branch just produces a value to return or assign — it's shorter, and the compiler checks that every possible case is handled (notice _ as the catch-all, similar to default). Leave out _ when the values you're matching are exhaustive on their own — for example, every case of an enum — and Dart will actually refuse to compile if you later add a new enum value and forget to handle it here.
Matching on type and pattern
switch can match more than plain equality. Combined with Dart's pattern support, you can branch on an object's shape:
String describe(Object value) {
return switch (value) {
int n when n < 0 => 'negative integer',
int n => 'integer: $n',
String s => 'string of length ${s.length}',
_ => 'something else',
};
}
print(describe(-4)); // negative integer
print(describe('hello')); // string of length 5Each case checks the runtime type of value and, if it matches, binds it to a typed variable (n, s) usable on the right of =>. The optional when clause adds a further condition beyond the type check alone — here, only negative integers take the first branch.
switch won't replace every if/else chain, but once you're comparing one value against three or more fixed possibilities, it's usually the clearer, safer choice.