Watch the video (10 min)
On this page23 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a switch Statement?
  5. 2. The Shape of a switch
  6. 3. Only One Case Runs
  7. 4. default: When Nothing Matches
  8. 5. Switching on a String
  9. 6. Several Lines in One Case
  10. 7. Empty Cases Share a Body
  11. 8. Combining Values with ||
  12. 9. Case Values Must Be Constants
  13. 10. switch or else-if?
  14. 11. A Real-World Example
  15. Code Examples
  16. Common Beginner Mistakes
  17. Best Practices
  18. Mini Challenge
  19. Practice Questions
  20. Practice Answers
  21. Quick Revision
  22. Key Takeaways
  23. What's Next?

Lecture 24 — switch Statements

Category5 — Control Flow
Lecture024 of 140
Estimated video length10 min
TargetDart 3.12.2
LevelBeginner

An else-if chain that compares one variable with value after value repeats the same test on every line. A switch statement 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, and toLowerCase() (Lecture 008)
  • ~/ and % (Lecture 017) and == (Lecture 018)
  • const values (Lecture 006)
  • if, else, and else-if chains (Lectures 022–023)

Connection With Previous Lectures

In Lecture 023 you learned to pick one branch out of many with else-if:

dart
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');
  }
}
output
Wednesday

It 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 switch statement does
  • Write a switch with case clauses and a default
  • Predict that only one case runs, with no break needed
  • 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 switch and an else-if chain
  • Recognize the error messages Dart produces for common switch mistakes

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:

dart
void main() {
  var day = 3;
  switch (day) {
    case 1:
      print('Monday');
    case 2:
      print('Tuesday');
    case 3:
      print('Wednesday');
    default:
      print('Another day');
  }
}
output
Wednesday

day 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:

output
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:

dart
void main() {
  var floor = 2;
  switch (floor) {
    case 1:
      print('Reception');
    case 2:
      print('Library');
    case 3:
      print('Cafeteria');
  }
  print('Done');
}
output
Library
Done

In 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:

dart
void main() {
  var choice = 9;
  switch (choice) {
    case 1:
      print('Start game');
    case 2:
      print('Settings');
    default:
      print('Unknown option: $choice');
  }
}
output
Unknown option: 9

default must be the last clause. Without one, a value that matches nothing simply runs nothing:

dart
void main() {
  var choice = 9;
  switch (choice) {
    case 1:
      print('Start game');
    case 2:
      print('Settings');
  }
  print('Menu closed');
}
output
Menu closed

5. Switching on a String

Any value you can compare with == works, including text:

dart
void main() {
  var command = 'stop';
  switch (command) {
    case 'start':
      print('Engine on');
    case 'stop':
      print('Engine off');
    default:
      print('Unknown command');
  }
}
output
Engine off

Matching 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:

dart
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');
  }
}
output
Level 2: Hard
Enemies: 12
Time limit: 60s

Each 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:

dart
void main() {
  var day = 'Sun';
  switch (day) {
    case 'Sat':
    case 'Sun':
      print('Weekend');
    default:
      print('Weekday');
  }
}
output
Weekend

This 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 ||.

dart
void main() {
  var day = 'Sat';
  switch (day) {
    case 'Sat' || 'Sun':
      print('Weekend');
    default:
      print('Weekday');
  }
}
output
Weekend

Read 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:

dart
const passMark = 50;

void main() {
  var marks = 50;
  switch (marks) {
    case passMark:
      print('Just passed!');
    default:
      print('Not exactly the pass mark');
  }
}
output
Just passed!

A normal var cannot be a case value:

dart
void main() {
  var limit = 10;
  var score = 10;
  switch (score) {
    case limit:
      print('Limit reached');
  }
}
output
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 valueseach 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.

dart
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');
  }
}
output
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

dart
void main() {
  var day = 5;
  switch (day) {
    case 1:
      print('Monday');
    case 5:
      print('Friday');
    case 7:
      print('Sunday');
    default:
      print('Midweek day');
  }
}
output
Friday

Example 2 — Falling Back to default

dart
void main() {
  var month = 13;
  switch (month) {
    case 1:
      print('January');
    case 12:
      print('December');
    default:
      print('No month number $month');
  }
}
output
No month number 13

Example 3 — Traffic Light

dart
void main() {
  var light = 'yellow';
  switch (light) {
    case 'green':
      print('Go');
    case 'yellow':
      print('Slow down');
    case 'red':
      print('Stop');
  }
}
output
Slow down

Example 4 — Ignoring Capital Letters

dart
void main() {
  var answer = 'YES';
  switch (answer.toLowerCase()) {
    case 'yes':
      print('Saved');
    case 'no':
      print('Cancelled');
    default:
      print('Please type yes or no');
  }
}
output
Saved

Example 5 — Empty Cases for Vowels

dart
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');
  }
}
output
e is a vowel

Example 6 — Even or Odd with %

dart
void main() {
  var ticket = 17;
  switch (ticket % 2) {
    case 0:
      print('Ticket $ticket: even — left queue');
    default:
      print('Ticket $ticket: odd — right queue');
  }
}
output
Ticket 17: odd — right queue

The switched value can be any expression; here it is the remainder, 1.

Example 7 — Student Marks

dart
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');
  }
}
output
Ali: Grade B

How it works

  1. 87 ~/ 10 is 8, so the marks are reduced to their "tens" digit.
  2. case 10 || 9 covers both 100 and the nineties.
  3. 8 matches the second case; the others are skipped.

Example 8 — Shopping Total by Delivery Zone

dart
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}');
}
output
Delivery: 200
Total: 1400

How it works

  1. delivery is declared before the switch so it can be used after it.
  2. Zone 'B' matches 'B' || 'C', which stores 200.
  3. The total is worked out once, after the switch has chosen the fee.

Example 9 — Bank Balance

dart
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');
}
output
Balance: 3500

How it works

  1. action is 'withdraw', so only balance -= amount runs.
  2. 5000 - 1500 leaves 3500.
  3. Changing action to 'deposit' would print Balance: 6500.

Example 10 — Temperature Conversion

dart
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');
  }
}
output
212.0 °F

How it works

  1. unit is 'C', so the Celsius-to-Fahrenheit formula runs.
  2. 100.0 * 9 / 5 + 32 is 212.0.
  3. The 'F' case is skipped, so its formula is never worked out.

Common Beginner Mistakes

1. Expecting a case to fall through

dart
void main() {
  var day = 'Sat';
  switch (day) {
    case 'Sat':
      print('Saturday');
    case 'Sun':
      print('Weekend'); // never runs for 'Sat'
  }
}
output
Saturday

A case with a body stops there. To share a body, use an empty case or ||.

2. Using a variable as a case value

dart
void main() {
  var limit = 10;
  var score = 10;
  switch (score) {
    // case limit: // ✗
    //   print('Limit reached');
  }
}
output
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

dart
void main() {
  var choice = 1;
  switch (choice) {
    // default: // ✗
    //   print('Other');
    case 1:
      print('One');
  }
}
output
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

dart
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:

output
warning - The matched value type 'int' can never be equal to this constant of type 'String'.

5. Writing the same case twice

dart
void main() {
  var day = 1;
  switch (day) {
    case 1:
      print('One');
    case 1: // never reached
      print('Uno');
  }
}
output
One

Only the first match runs. dart analyze reports: warning - This case is covered by the previous cases.

6. Forgetting the parentheses

dart
void main() {
  var day = 3;
  // switch day { // ✗
  switch (day) {
    case 3:
      print('Wednesday');
  }
}
output
Error: Expected to find '('.

The value after switch always goes in parentheses, just like the condition of an if.


Best Practices

  • Reach for switch when one value is compared with several fixed values.
  • Add a default whenever 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:

output
Zayan's answer: a
Correct!

Try it yourself before opening the solution.

Show solution
dart
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');
  }
}
output
Zayan's answer: a
Correct!

How it works

  1. toLowerCase() turns 'A' and 'a' into the same value, halving the cases.
  2. 'b' || 'c' || 'd' shares one body among three wrong answers.
  3. default catches 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

  1. Store number = 2 and use a switch to print One, Two, or Three for 1, 2, 3.
  2. Add a default to question 1 that prints Too big, and run it with number = 8.
  3. Store color = 'red' and print Stop for 'red' and Go for 'green'.

Application

  1. Store month = 2. Print 31 days for 1 and 3, 28 days for 2, using empty cases for 1 and 3.

  2. Rewrite question 4 using || instead of empty cases.

  3. Store size = 'M'. Print the price: 'S' → Price: 300, 'M' → Price: 400, 'L' → Price: 500, anything else → Unknown size.

  4. What does this print? Explain why.

    dart
    void main() {
      var x = 1;
      switch (x) {
        case 1:
          print('A');
        case 2:
          print('B');
      }
      print('C');
    }
  5. Rewrite this chain as a switch, keeping the output:

    dart
    void main() {
      var command = 'help';
      if (command == 'start') {
        print('Starting');
      } else if (command == 'help') {
        print('Showing help');
      } else {
        print('Unknown');
      }
    }

Challenge

  1. Sara's marks are 64. Using marks ~/ 10 in a switch, print Grade A for 90–100, Grade B for 80–89, Grade C for 60–79, and Grade F otherwise.
  2. A cinema charges by day: 'Mon' to 'Thu' → 500, 'Fri' → 700, 'Sat' and 'Sun' → 800. Store day = 'FRI' and tickets = 3, ignore capital letters, and print Total: 2100.

Practice Answers

Question 1 — Solution

dart
void main() {
  var number = 2;
  switch (number) {
    case 1:
      print('One');
    case 2:
      print('Two');
    case 3:
      print('Three');
  }
}
output
Two

Question 2 — Solution

dart
void main() {
  var number = 8;
  switch (number) {
    case 1:
      print('One');
    case 2:
      print('Two');
    case 3:
      print('Three');
    default:
      print('Too big');
  }
}
output
Too big

Question 3 — Solution

dart
void main() {
  var color = 'red';
  switch (color) {
    case 'red':
      print('Stop');
    case 'green':
      print('Go');
  }
}
output
Stop

Question 4 — Solution

dart
void main() {
  var month = 2;
  switch (month) {
    case 1:
    case 3:
      print('31 days');
    case 2:
      print('28 days');
  }
}
output
28 days

Question 5 — Solution

dart
void main() {
  var month = 2;
  switch (month) {
    case 1 || 3:
      print('31 days');
    case 2:
      print('28 days');
  }
}
output
28 days

Question 6 — Solution

dart
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');
  }
}
output
Price: 400

Question 7 — Solution

output
A
C

case 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

dart
void main() {
  var command = 'help';
  switch (command) {
    case 'start':
      print('Starting');
    case 'help':
      print('Showing help');
    default:
      print('Unknown');
  }
}
output
Showing help

Question 9 — Solution

dart
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');
  }
}
output
Grade C

64 ~/ 10 is 6, which matches 7 || 6.

Question 10 — Solution

dart
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}');
}
output
Total: 2100

'FRI' becomes 'fri', so price is 700, and 700 * 3 is 2100.


Quick Revision

  1. What does a switch statement compare its value with?
  2. How many case bodies run when a value matches?
  3. Do you need break at the end of a case in Dart 3?
  4. When does default run, and where must it go?
  5. How do you make two values share one body? Name both ways.
  6. Why can't a normal var be a case value?
  7. When is an else-if chain a better choice than switch?

Key Takeaways

  • A switch statement checks one value against a list of case values, top to bottom.
  • The first matching case runs, then the switch ends — no break needed in Dart 3.
  • default catches 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 switch for "which value?", and else-if for "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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.