On this page12 sections
Lecture 019: switch & case
| Day | 7: Conditional Expressions & switch |
| Lecture | 019 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
When one value decides between many outcomes (menu option 1, 2, 3 or 4; a command like "start" or "stop"), a long else-if ladder repeats the same variable again and again.
switchchecks one value against a list of cases, neatly.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 015–016 (operators, if-else ladder).
Learning Objectives
- Write a
switchstatement withcaseanddefault - Switch on numbers and strings
- Share one block between cases with
|| - Use comparison cases like
case >= 80: - Write a
switchexpression that produces a value
1. The switch Statement
switch (value) {
case firstOption:
// runs when value == firstOption
case secondOption:
// ...
default:
// runs when nothing else matched
}var day = 3;
switch (day) {
case 1:
print('Monday');
case 2:
print('Tuesday');
case 3:
print('Wednesday');
default:
print('Another day');
}
// WednesdayDart compares day with each case from the top, runs the first match, and stops. You don't
need break. default is optional and works like the final else of a ladder.
2. Strings Work Too
var command = 'stop';
switch (command) {
case 'start':
print('Starting...');
case 'stop':
print('Stopping...');
default:
print('Unknown command');
}
// Stopping...3. Several Values, One Block
Use || between values:
var grade = 'B';
switch (grade) {
case 'A' || 'B':
print('Great work');
case 'C':
print('Good');
default:
print('Keep practising');
}
// Great workLecture 052 shows another way: empty cases that fall through.
4. Comparison Cases
A case can compare instead of matching exactly. Like a ladder, the first true case wins:
var marks = 72;
switch (marks) {
case >= 80:
print('A');
case >= 70:
print('B');
case >= 50:
print('C');
default:
print('F');
}
// B5. switch Expressions: Choose a Value
When each case just produces a value, a switch expression is shorter. Use => for each
case, _ for "anything else", and end with ;:
var month = 2;
var name = switch (month) {
1 => 'January',
2 => 'February',
3 => 'March',
_ => 'Later in the year',
};
print(name); // February| switch statement | switch expression |
|---|---|
| runs statements for each case | produces one value |
case x: and default: | x => and _ => |
no ; after the closing } | ends with }; |
Code Examples
Example 1: An ATM Menu
void main() {
var choice = 2;
var amount = 3000;
print('1. Check balance 2. Withdraw 3. Deposit 4. Exit');
print('You chose: $choice');
switch (choice) {
case 1:
print('Your balance is Rs 10000');
case 2:
print('Withdrawing Rs $amount');
print('Please take your cash');
case 3:
print('Depositing Rs $amount');
case 4:
print('Goodbye!');
default:
print('Invalid choice');
}
var fee = switch (amount) {
< 1000 => 0,
< 5000 => 10,
_ => 25,
};
print('Fee: Rs $fee');
}Output
1. Check balance 2. Withdraw 3. Deposit 4. Exit
You chose: 2
Withdrawing Rs 3000
Please take your cash
Fee: Rs 10A case can hold several lines (case 2 prints two). The fee uses a switch expression with comparison cases.
Common Beginner Mistakes
1. Forgetting the colon
case 1
print('Monday');Error: Expected ':' before this.2. A switch expression that doesn't cover every value
var name = switch (month) {
1 => 'January',
2 => 'February',
};Error: The type 'int' is not exhaustively matched by the switch cases since it doesn't match 'int()'.
Try adding a wildcard pattern or cases that match 'int()'.An expression must always produce a value. Add _ => ... at the end.
3. Repeating a case: a second case 'A': can never run. Dart's analyzer warns: "This case is
covered by the previous cases."
4. Expecting fall-through: in Dart, a case with code never runs into the next case. See Lecture 052.
Practice Questions
- What prints when
dayis9in the Section 1 example? - Do you need
breakat the end of each case in Dart? - Write a case that matches both
'sat'and'sun'. - Turn this into a switch expression:
1→'one',2→'two', anything else →'many'. - Why must a switch expression end with
_ => ...(or cover every value)?
Practice Answers
Another day(fromdefault).- No. Each case stops on its own.
case 'sat' || 'sun':
var word = switch (n) {
1 => 'one',
2 => 'two',
_ => 'many',
};- An expression must always produce a value, so every possible input needs a case.
Key Takeaways
switchchecks one value against manycases; the first match runs, then it stops.defaultcatches everything else;case a || b:shares a block.- Cases can compare:
case >= 80:. - A switch expression (
x => value,_ => value) produces a value and must cover every case.