On this page23 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a switch Statement?
- 2. The Shape of a switch
- 3. Only One Case Runs
- 4. default: When Nothing Matches
- 5. Switching on a String
- 6. Several Lines in One Case
- 7. Empty Cases Share a Body
- 8. Combining Values with ||
- 9. Case Values Must Be Constants
- 10. switch or else-if?
- 11. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 24 — switch Statements
| Category | 5 — Control Flow |
| Lecture | 024 of 140 |
| Estimated video length | 10 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
An
else-ifchain that compares one variable with value after value repeats the same test on every line. Aswitchstatement names the value once and lists the possible matches beneath it.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 004–023:
- variables,
int,String, string interpolation, andtoLowerCase()(Lecture 008) ~/and%(Lecture 017) and==(Lecture 018)constvalues (Lecture 006)if,else, andelse-ifchains (Lectures 022–023)
Connection With Previous Lectures
In Lecture 023 you learned to pick one branch out of many with else-if:
void main() {
var day = 3;
if (day == 1) {
print('Monday');
} else if (day == 2) {
print('Tuesday');
} else if (day == 3) {
print('Wednesday');
} else {
print('Another day');
}
}WednesdayIt works, but look at what repeats: day == on every line. Each branch asks the same question
about the same variable, only with a different value. With seven days, the chain grows long,
and a typo like dya == 4 hides in the middle. Dart has a statement built for exactly this
shape.
Learning Objectives
By the end of this lecture you will be able to:
- Explain what a
switchstatement does - Write a
switchwithcaseclauses and adefault - Predict that only one case runs, with no
breakneeded - Let several values share one body with empty cases
- Combine values in one case with
|| - Recognize that case values must be constants of a matching type
- Choose between
switchand anelse-ifchain - Recognize the error messages Dart produces for common
switchmistakes
1. What Is a switch Statement?
A switch statement takes one value and compares it with a list of possible values, called
cases. The first case that matches runs; the rest are skipped.
Analogy — think of a lift. You press one button, and the lift stops at that floor only. It doesn't stop at every floor on the way to ask "is this the one?"
Here is the day program again, as a switch:
void main() {
var day = 3;
switch (day) {
case 1:
print('Monday');
case 2:
print('Tuesday');
case 3:
print('Wednesday');
default:
print('Another day');
}
}Wednesdayday is written once. Each case lists only the value it is waiting for.
2. The Shape of a switch
Every part has a fixed place:
switch (value) { ← the value to check, in parentheses
case 1: ← "if value == 1" — note the colon
print('...'); ← the case body: the code that runs
default: ← "anything else" (optional, always last)
print('...');
}Dart compares the value with each case from top to bottom, using == exactly as in
Lecture 018. The body of a case is every line under it until the next case or default.
3. Only One Case Runs
When a case matches, its body runs and the whole switch is finished. Dart does not
continue into the next case:
void main() {
var floor = 2;
switch (floor) {
case 1:
print('Reception');
case 2:
print('Library');
case 3:
print('Cafeteria');
}
print('Done');
}Library
DoneIn many older languages — and in Dart before version 3 — every case had to end with break,
or the program would "fall through" into the next case. Modern Dart ends the case for you.
You may still see break; in older code; it is allowed, but it adds nothing.
4. default: When Nothing Matches
default runs when no case matches — just like the final else of a chain:
void main() {
var choice = 9;
switch (choice) {
case 1:
print('Start game');
case 2:
print('Settings');
default:
print('Unknown option: $choice');
}
}Unknown option: 9default must be the last clause. Without one, a value that matches nothing simply runs
nothing:
void main() {
var choice = 9;
switch (choice) {
case 1:
print('Start game');
case 2:
print('Settings');
}
print('Menu closed');
}Menu closed5. Switching on a String
Any value you can compare with == works, including text:
void main() {
var command = 'stop';
switch (command) {
case 'start':
print('Engine on');
case 'stop':
print('Engine off');
default:
print('Unknown command');
}
}Engine offMatching is exact, so 'Stop' would not match 'stop'. When the text comes from a person,
switch on command.toLowerCase() and write the cases in lowercase.
6. Several Lines in One Case
A case body can hold as many statements as you need — no braces required:
void main() {
var level = 2;
switch (level) {
case 1:
print('Level 1: Easy');
print('Enemies: 5');
case 2:
print('Level 2: Hard');
print('Enemies: 12');
print('Time limit: 60s');
}
}Level 2: Hard
Enemies: 12
Time limit: 60sEach case body is its own little block, so two cases may each declare a variable with the same name.
7. Empty Cases Share a Body
Sometimes several values need the same code. Stack the cases, leaving all but the last one empty:
void main() {
var day = 'Sun';
switch (day) {
case 'Sat':
case 'Sun':
print('Weekend');
default:
print('Weekday');
}
}WeekendThis is the one place Dart "falls through": an empty case has nothing to run, so it continues to the next body. A case with even one statement never does.
8. Combining Values with ||
Dart 3 offers a shorter way to say the same thing: list the values in one case, joined by
||.
void main() {
var day = 'Sat';
switch (day) {
case 'Sat' || 'Sun':
print('Weekend');
default:
print('Weekday');
}
}WeekendRead case 'Sat' || 'Sun': as "the value is 'Sat' or 'Sun'". It is the same || idea
from Lecture 019, used inside a case. Both styles from sections 7 and 8 are correct; || keeps
it on one line.
Cases can match far more than single values — ranges like >= 90, and whole shapes of data.
Those are patterns: a first taste in Lecture 025, and the full story in Lecture 077 —
Introduction to Patterns.
9. Case Values Must Be Constants
A case value has to be known before the program runs — a literal like 3 or 'Sat', or a
const variable:
const passMark = 50;
void main() {
var marks = 50;
switch (marks) {
case passMark:
print('Just passed!');
default:
print('Not exactly the pass mark');
}
}Just passed!A normal var cannot be a case value:
void main() {
var limit = 10;
var score = 10;
switch (score) {
case limit:
print('Limit reached');
}
}Error: Not a constant expression.
case limit:
^^^^^10. switch or else-if?
Use switch when… | Use else-if when… |
|---|---|
| one value is compared with fixed values | each branch tests a different condition |
day is 1, 2, 3… | marks >= 80, then marks >= 60… |
command is 'start', 'stop'… | conditions mix && and ` |
A switch answers "which value is it?". An else-if chain answers "which condition is
true?".
11. A Real-World Example
A café's ordering screen: one code, several items, some sharing a price.
void main() {
var customer = 'Sara';
var code = 'L';
var size = 'large';
switch (code) {
case 'T' || 'C':
print('$customer ordered tea or coffee: 150');
case 'L':
print('$customer ordered a latte: 250');
switch (size) {
case 'large':
print('Large size: +50');
default:
print('Regular size');
}
case 'W':
print('$customer ordered water: 50');
default:
print('Sorry, code $code is not on the menu');
}
}Sara ordered a latte: 250
Large size: +50'T' || 'C' shares one body, the latte case runs several statements — including a second
switch inside it — and default catches unknown codes. Only one case of each switch ran.
Code Examples
Example 1 — Day Number to Name
void main() {
var day = 5;
switch (day) {
case 1:
print('Monday');
case 5:
print('Friday');
case 7:
print('Sunday');
default:
print('Midweek day');
}
}FridayExample 2 — Falling Back to default
void main() {
var month = 13;
switch (month) {
case 1:
print('January');
case 12:
print('December');
default:
print('No month number $month');
}
}No month number 13Example 3 — Traffic Light
void main() {
var light = 'yellow';
switch (light) {
case 'green':
print('Go');
case 'yellow':
print('Slow down');
case 'red':
print('Stop');
}
}Slow downExample 4 — Ignoring Capital Letters
void main() {
var answer = 'YES';
switch (answer.toLowerCase()) {
case 'yes':
print('Saved');
case 'no':
print('Cancelled');
default:
print('Please type yes or no');
}
}SavedExample 5 — Empty Cases for Vowels
void main() {
var letter = 'e';
switch (letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
print('$letter is a vowel');
default:
print('$letter is a consonant');
}
}e is a vowelExample 6 — Even or Odd with %
void main() {
var ticket = 17;
switch (ticket % 2) {
case 0:
print('Ticket $ticket: even — left queue');
default:
print('Ticket $ticket: odd — right queue');
}
}Ticket 17: odd — right queueThe switched value can be any expression; here it is the remainder, 1.
Example 7 — Student Marks
void main() {
var student = 'Ali';
var marks = 87;
switch (marks ~/ 10) {
case 10 || 9:
print('$student: Grade A');
case 8:
print('$student: Grade B');
case 7:
print('$student: Grade C');
default:
print('$student: Grade F');
}
}Ali: Grade BHow it works
87 ~/ 10is8, so the marks are reduced to their "tens" digit.case 10 || 9covers both100and the nineties.8matches the second case; the others are skipped.
Example 8 — Shopping Total by Delivery Zone
void main() {
var subtotal = 1200;
var zone = 'B';
var delivery = 0;
switch (zone) {
case 'A':
delivery = 100;
case 'B' || 'C':
delivery = 200;
default:
delivery = 500;
}
print('Delivery: $delivery');
print('Total: ${subtotal + delivery}');
}Delivery: 200
Total: 1400How it works
deliveryis declared before theswitchso it can be used after it.- Zone
'B'matches'B' || 'C', which stores200. - The total is worked out once, after the
switchhas chosen the fee.
Example 9 — Bank Balance
void main() {
var balance = 5000;
var action = 'withdraw';
var amount = 1500;
switch (action) {
case 'deposit':
balance += amount;
case 'withdraw':
balance -= amount;
default:
print('Unknown action');
}
print('Balance: $balance');
}Balance: 3500How it works
actionis'withdraw', so onlybalance -= amountruns.5000 - 1500leaves3500.- Changing
actionto'deposit'would printBalance: 6500.
Example 10 — Temperature Conversion
void main() {
var temperature = 100.0;
var unit = 'C';
switch (unit) {
case 'C':
print('${temperature * 9 / 5 + 32} °F');
case 'F':
print('${(temperature - 32) * 5 / 9} °C');
default:
print('Unknown unit: $unit');
}
}212.0 °FHow it works
unitis'C', so the Celsius-to-Fahrenheit formula runs.100.0 * 9 / 5 + 32is212.0.- The
'F'case is skipped, so its formula is never worked out.
Common Beginner Mistakes
1. Expecting a case to fall through
void main() {
var day = 'Sat';
switch (day) {
case 'Sat':
print('Saturday');
case 'Sun':
print('Weekend'); // never runs for 'Sat'
}
}SaturdayA case with a body stops there. To share a body, use an empty case or ||.
2. Using a variable as a case value
void main() {
var limit = 10;
var score = 10;
switch (score) {
// case limit: // ✗
// print('Limit reached');
}
}Error: Not a constant expression.Make it const limit = 10;, or use an if when the value is only known at run time.
3. Putting default first
void main() {
var choice = 1;
switch (choice) {
// default: // ✗
// print('Other');
case 1:
print('One');
}
}Error: The default case should be the last case in a switch statement.
Try moving the default case after the other case clauses.4. Cases of the wrong type
void main() {
var day = 3;
switch (day) {
case 'Wednesday': // never matches an int
print('Midweek');
}
}The program runs and prints nothing — 3 is never equal to 'Wednesday'. dart analyze
warns you:
warning - The matched value type 'int' can never be equal to this constant of type 'String'.5. Writing the same case twice
void main() {
var day = 1;
switch (day) {
case 1:
print('One');
case 1: // never reached
print('Uno');
}
}OneOnly the first match runs. dart analyze reports: warning - This case is covered by the previous cases.
6. Forgetting the parentheses
void main() {
var day = 3;
// switch day { // ✗
switch (day) {
case 3:
print('Wednesday');
}
}Error: Expected to find '('.The value after switch always goes in parentheses, just like the condition of an if.
Best Practices
- Reach for
switchwhen one value is compared with several fixed values. - Add a
defaultwhenever an unexpected value is possible, and give it a helpful message. - Leave out
break— Dart 3 ends each case automatically. - Share a body with
||(or empty cases) instead of copying the same code. - Normalize text first, e.g.
switch (input.toLowerCase()). - Keep case bodies short; long logic inside a case is hard to follow.
Mini Challenge
Zayan's quiz app gets an answer letter. 'A' and 'a' are correct; 'B', 'C', and 'D'
(in either case) are wrong; anything else is invalid. With answer = 'a', print:
Zayan's answer: a
Correct!Try it yourself before opening the solution.
Show solution
void main() {
var answer = 'a';
print("Zayan's answer: $answer");
switch (answer.toLowerCase()) {
case 'a':
print('Correct!');
case 'b' || 'c' || 'd':
print('Wrong, try again');
default:
print('Invalid answer');
}
}Zayan's answer: a
Correct!How it works
toLowerCase()turns'A'and'a'into the same value, halving the cases.'b' || 'c' || 'd'shares one body among three wrong answers.defaultcatches anything that is not a letter from A to D.
Practice Questions
Work through these in order — they run from beginner to application to challenge. Every question gives you exact values, so you can compare your output with the answers.
Beginner
- Store
number = 2and use aswitchto printOne,Two, orThreefor1,2,3. - Add a
defaultto question 1 that printsToo big, and run it withnumber = 8. - Store
color = 'red'and printStopfor'red'andGofor'green'.
Application
-
Store
month = 2. Print31 daysfor 1 and 3,28 daysfor 2, using empty cases for 1 and 3. -
Rewrite question 4 using
||instead of empty cases. -
Store
size = 'M'. Print the price:'S'→Price: 300,'M'→Price: 400,'L'→Price: 500, anything else →Unknown size. -
What does this print? Explain why.
void main() { var x = 1; switch (x) { case 1: print('A'); case 2: print('B'); } print('C'); } -
Rewrite this chain as a
switch, keeping the output:void main() { var command = 'help'; if (command == 'start') { print('Starting'); } else if (command == 'help') { print('Showing help'); } else { print('Unknown'); } }
Challenge
- Sara's marks are
64. Usingmarks ~/ 10in aswitch, printGrade Afor 90–100,Grade Bfor 80–89,Grade Cfor 60–79, andGrade Fotherwise. - A cinema charges by
day:'Mon'to'Thu'→500,'Fri'→700,'Sat'and'Sun'→800. Storeday = 'FRI'andtickets = 3, ignore capital letters, and printTotal: 2100.
Practice Answers
Question 1 — Solution
void main() {
var number = 2;
switch (number) {
case 1:
print('One');
case 2:
print('Two');
case 3:
print('Three');
}
}TwoQuestion 2 — Solution
void main() {
var number = 8;
switch (number) {
case 1:
print('One');
case 2:
print('Two');
case 3:
print('Three');
default:
print('Too big');
}
}Too bigQuestion 3 — Solution
void main() {
var color = 'red';
switch (color) {
case 'red':
print('Stop');
case 'green':
print('Go');
}
}StopQuestion 4 — Solution
void main() {
var month = 2;
switch (month) {
case 1:
case 3:
print('31 days');
case 2:
print('28 days');
}
}28 daysQuestion 5 — Solution
void main() {
var month = 2;
switch (month) {
case 1 || 3:
print('31 days');
case 2:
print('28 days');
}
}28 daysQuestion 6 — Solution
void main() {
var size = 'M';
switch (size) {
case 'S':
print('Price: 300');
case 'M':
print('Price: 400');
case 'L':
print('Price: 500');
default:
print('Unknown size');
}
}Price: 400Question 7 — Solution
A
Ccase 1 matches and prints A. The case has a body, so it does not fall into case 2. The
switch ends and print('C') runs after it.
Question 8 — Solution
void main() {
var command = 'help';
switch (command) {
case 'start':
print('Starting');
case 'help':
print('Showing help');
default:
print('Unknown');
}
}Showing helpQuestion 9 — Solution
void main() {
var marks = 64;
switch (marks ~/ 10) {
case 10 || 9:
print('Grade A');
case 8:
print('Grade B');
case 7 || 6:
print('Grade C');
default:
print('Grade F');
}
}Grade C64 ~/ 10 is 6, which matches 7 || 6.
Question 10 — Solution
void main() {
var day = 'FRI';
var tickets = 3;
var price = 0;
switch (day.toLowerCase()) {
case 'mon' || 'tue' || 'wed' || 'thu':
price = 500;
case 'fri':
price = 700;
case 'sat' || 'sun':
price = 800;
}
print('Total: ${price * tickets}');
}Total: 2100'FRI' becomes 'fri', so price is 700, and 700 * 3 is 2100.
Quick Revision
- What does a
switchstatement compare its value with? - How many case bodies run when a value matches?
- Do you need
breakat the end of a case in Dart 3? - When does
defaultrun, and where must it go? - How do you make two values share one body? Name both ways.
- Why can't a normal
varbe a case value? - When is an
else-ifchain a better choice thanswitch?
Key Takeaways
- A
switchstatement checks one value against a list ofcasevalues, top to bottom. - The first matching case runs, then the
switchends — nobreakneeded in Dart 3. defaultcatches everything else and must come last; without it, no match means nothing runs.- Empty cases fall through to the next body; a case with a body never does.
case 'Sat' || 'Sun':lets several values share one body on one line.- Case values must be constants, and should have the same type as the switched value.
- Use
switchfor "which value?", andelse-iffor "which condition?".
What's Next?
Lecture 025 — Modern Switch Expressions. Look back at Example 8 and Question 10: each case
does nothing but pick a value, yet we still needed a variable declared beforehand and an
assignment in every case. Dart 3 can turn the whole switch into a single expression that produces
a value directly — shorter, safer, and the gateway to patterns.