Control Flow: Decisions and Loops
So far, our programs have marched straight from top to bottom. Real programs need to make choices and repeat work. Control flow is the set of tools that let a program decide what to do and how often to do it.
Making decisions with if and else
The if statement runs a block of code only when a condition is true. A condition is an expression that evaluates to true or false, like age >= 18.
void main() {
int temperature = 31;
if (temperature > 30) {
print('Stay hydrated!');
} else if (temperature < 10) {
print('Bundle up.');
} else {
print('Pleasant weather.');
}
}Dart checks each condition in order and runs the first block that matches. If none match, the else block runs. Note that the condition must be a real bool — Dart will not secretly treat numbers as true or false like some languages do.
Choosing between values with switch
When you compare one value against many options, switch is cleaner than a long chain of ifs:
void main() {
String command = 'pause';
switch (command) {
case 'start':
print('Starting...');
break;
case 'pause':
print('Pausing.');
break;
default:
print('Unknown command: $command');
}
}Repeating work with loops
Loops run code more than once. The for loop is the workhorse: it repeats a counted number of times.
void main() {
for (var i = 1; i <= 3; i++) {
print('Lap $i');
}
}This prints "Lap 1" through "Lap 3". The three parts set up the counter, state when to keep going, and increase the counter each pass.
When you have a collection, such as a list, you can loop over each element directly:
void main() {
var fruits = ['apple', 'banana', 'cherry'];
for (var fruit in fruits) {
print('I like $fruit');
}
}The while loop is different: it keeps going as long as its condition is true. Use it when you do not know in advance how many times you need to repeat:
void main() {
int battery = 100;
while (battery > 20) {
print('Battery at $battery%');
battery -= 30;
}
print('Please charge me.');
}Be careful: if the condition never becomes false, the loop runs forever.
diagram mermaid caption: How a while loop flows through its condition, body, and back again. alt: A flowchart where a condition is checked; if false the loop exits, if true the loop body runs and control returns to the condition.
flowchart TD
A[Start] --> B{Condition true?}
B -- No --> E[Exit loop]
B -- Yes --> C[Run loop body]
C --> BBreaking out and skipping ahead
Two small keywords give you fine control. break leaves a loop immediately. continue skips the rest of the current pass and starts the next one:
void main() {
for (var i = 1; i <= 5; i++) {
if (i == 3) continue; // skip 3
if (i == 5) break; // stop before printing 5
print(i);
}
}This prints 1, 2, and 4.
callout tip Dart also has a modern switch expression that returns a value directly. We will meet it in later chapters once functions are familiar.
exercise Q: What does this program print?
for (var i = 1; i <= 4; i++) {
if (i == 2) continue;
print(i);
}A: It prints 1, then 3, then 4. The value 2 is skipped by continue, and the loop ends normally after 4.
estimate minutes: 25
Spotted a mistake, or code that does not work?