Sub topic 5
Control flow: conditions and loops
We assume you know Dart variables, Boolean values, lists, and basic expressions. Control flow is the order in which Dart runs statements. Conditions choose between paths. Loops repeat a path.
Conditions with `if`
An if statement runs its block when its condition is true. Dart conditions must produce a bool; values such as 0 and '' cannot act as Boolean values.
void main() {
final temperature = 23;
if (temperature >= 30) {
print('Hot');
} else if (temperature >= 20) {
print('Comfortable');
} else {
print('Cool');
}
}The conditions are checked from top to bottom. Dart runs the first matching block and skips the remaining branches.
For a short choice, use Dart’s conditional expression:
final label = temperature >= 20 ? 'comfortable' : 'cool';The expression before ? is the condition. Dart evaluates the expression before : when the condition is true and the other expression when it is false.
`switch` for several known cases
Use switch when one value can have several distinct cases. Each case can contain statements.
void describe(String status) {
switch (status) {
case 'ready':
print('Start the task');
case 'waiting':
print('Wait for input');
default:
print('Unknown status');
}
}
void main() {
describe('ready');
}In Dart, a non-empty case does not fall through to the next case. If you need several values to share a result, combine cases with a comma:
String priorityLabel(int priority) {
switch (priority) {
case 1:
case 2:
return 'high';
case 3:
return 'normal';
default:
return 'low';
}
}A common error is forgetting a default branch when unexpected input is possible.
Repeating work with loops
A for loop is useful when you have a starting value, a stopping condition, and an update.
void main() {
var total = 0;
for (var number = 1; number <= 5; number++) {
total += number;
}
print(total); // 15
}A for-in loop visits each item in an iterable, such as a list:
void main() {
final names = ['Ada', 'Linus', 'Grace'];
for (final name in names) {
print(name);
}
}Use while when the number of repetitions depends on a condition:
void main() {
var attempts = 0;
while (attempts < 3) {
print('Attempt ${attempts + 1}');
attempts++;
}
}A do-while loop always runs its body at least once:
var input = '';
do {
input = 'ready';
} while (input != 'ready');Use break to leave a loop early and continue to skip to its next iteration. Make sure every while loop can eventually make its condition false, or it will run forever.
Exercise
What does this code print? for (var i = 0; i < 4; i++) { if (i == 2) continue; print(i); }
Show answer
It prints 0, 1, and 3. continue skips printing when i is 2.