Back to quest
Control Flow & FunctionsLevel 16 / 32

Conditions (If/Else & Switch)

Controlling program flow with conditional logic

Conditions allow your program to "think". They let your app decide which code to run based on the state of your data.

1. If / Else & Nesting

You can nest conditions within each other, but be careful not to make the code too hard to read (this is often called "Spaghetti Code").

Nested Logic

example.dart
1bool hasTicket = true;
2bool isVIP = false;
3int age = 16;
4 
5if (hasTicket) {
6 if (age >= 18) {
7 print('Welcome to the concert!');
8 if (isVIP) {
9 print('Please go to the VIP lounge.');
10 }
11 } else {
12 print('Sorry, this is an 18+ event.');
13 }
14} else {
15 print('You need to buy a ticket.');
16}

HintWhile nesting works, often "Guard Clauses" (returning early) are cleaner. Example: if (!hasTicket) return;

2. Switch Statements & Logic

Switch statements in Dart compare integer, string, or compile-time constants using ==. The comparison must be exact.

Switch Semantics

example.dart
1var command = 'OPEN';
2 
3switch (command) {
4 case 'OPEN':
5 print('Opening...');
6 // In Dart, non-empty cases MUST end with break, continue, return, or throw.
7 break;
8
9 case 'CLOSED':
10 case 'LOCKED':
11 // This is "Fallthrough": Both CLOSED and LOCKED run this code.
12 print('The door is secure.');
13 break;
14 
15 default:
16 print('Unknown state.');
17}

HintFallthrough (letting one case run into the next) is only allowed in Dart if the case body is empty.

3. Ternary Operator as Logic

For simple assignments based on a condition, the Ternary Operator is a clean syntax replacement for if-else.

Concise Assignment

example.dart
1int stock = 0;
2 
3// Long way
4String status;
5if (stock > 0) {
6 status = 'In Stock';
7} else {
8 status = 'Out of Stock';
9}
10 
11// Short way (Ternary)
12String quickStatus = stock > 0 ? 'In Stock' : 'Out of Stock';

HintStructure: condition ? value_if_true : value_if_false. Use this only for short, simple logic.

Loot collected

Key takeaways
  • Use if/else for simple binary decisions.
  • Use else if for checking ranges or multiple conditions.
  • Use switch when checking one variable against known constants.
  • Code execution stops after the first true condition in an if chain.

Side quests

Practice exercises

1

Exercise 1: Voting Age

Write an if statement that prints "Adult" if age is 18 or more.

Reveal solution
solution.dart
1if (age >= 18) print('Adult');
2

Exercise 2: Switch It

Create a switch statement for a variable grade ("A", "B", "C") that prints a message for each.

Reveal solution
solution.dart
1switch(grade) { case 'A': print('Great!'); break; ... }
Party chat

Comments