What is Switch?
The switch statement matches a value against a list of case patterns and executes the matching block. It is cleaner than a long chain of else if when comparing one variable against many fixed values.
Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// runs if no case matches
}
Example
void main() {
String day = 'Monday';
switch (day) {
case 'Monday':
print('Start of the work week!');
break;
case 'Friday':
print('Almost the weekend!');
break;
case 'Saturday':
case 'Sunday':
print('It is the weekend!');
break;
default:
print('A regular weekday.');
}
int statusCode = 404;
switch (statusCode) {
case 200: print('OK'); break;
case 201: print('Created'); break;
case 404: print('Not Found'); break;
case 500: print('Server Error'); break;
default: print('Unknown status');
}
}
Output:Start of the work week!
Not Found
Switch Expressions (Dart 3)
Dart 3 introduced switch expressions — a concise inline form that returns a value:
String result = switch (statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
_ => 'Unknown',
};
print(result);
⚠️ Common Mistakes
- Forgetting
break — without it, execution falls through to the next case.
- Using a non-constant expression in a case value.
🧠 Quiz
1. What happens if no case matches and there is no default?
- A) Error
- B) Nothing happens ✅
- C) First case runs
- D) Program crashes
2. In Dart 3, what symbol separates the case pattern from the result in a switch expression?
Summary
The switch statement matches a value against constant cases and executes the first match. Always use break to prevent fall-through. Dart 3 adds switch expressions for inline, concise value switching using =>.