Dart If Else
An if statement runs a block of code only when its condition is true. An else block runs when the same condition is false.
A simple if
The condition is true, so the block runs. The greeting reaches the screen.
void main() {
var age = 20;
if (age >= 18) {
print('Adult');
}
}If and else
The condition is false, so the else block runs. The screen shows the else line.
void main() {
var age = 15;
if (age >= 18) {
print('Adult');
} else {
print('Young');
}
}An else if chain
The first test fails and the second test passes. The screen shows the middle line.
void main() {
var score = 75;
if (score >= 90) {
print('Top');
} else if (score >= 60) {
print('Pass');
} else {
print('Retry');
}
}A combined condition
Both parts of the condition are true. The block runs and shows its line.
void main() {
var day = 'Saturday';
var sunny = true;
if (day == 'Saturday' && sunny) {
print('Trip day');
}
}Example
void main() {
var temp = 24;
if (temp >= 30) {
print('Hot');
} else if (temp >= 18) {
print('Warm');
} else {
print('Cold');
}
}Key points
- Use if to run code when a condition is true.
- The condition sits in round brackets after the word if.
- The block sits in curly brackets after the condition.
- Use else to run code when the condition is false.
- Use else if to test a new condition when the first one is false.
- Dart tests the conditions from the top down.
In this example, temp holds 24. The first test asks if 24 reaches 30, and the answer is false. The next test asks if 24 reaches 18, and the answer is true. The Warm block runs, and the else block never runs.
Note
An if statement in Dart gives no value. It only chooses which block runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
When does an else block run?