Conditionals: if and else
Prerequisites: Operators
A conditional runs code only when a condition is true.
Real-world analogy: "If it's raining, take an umbrella; otherwise, wear sunglasses."
Syntax
if (condition) {
// runs when condition is true
} else if (otherCondition) {
// runs when the first was false and this one is true
} else {
// runs when none of the above were true
}
Example
void main() {
const temperature = 18;
if (temperature > 25) {
print("It's hot");
} else if (temperature > 15) {
print("It's pleasant");
} else {
print("It's cold");
}
}
Expected output
It's pleasant
Dart checks each condition top to bottom and runs only the first
branch that matches. For choosing between two values, the conditional
operator ? : from the Operators lesson is often neater.
Common mistakes
- Forgetting the parentheses:
if age > 18doesn't compile. - Putting conditions in the wrong order.
if (score > 50)beforeif (score > 90)means the second can never run.
Practice
Store an age and print adult for 18 and over, teen for 13–17, and
child otherwise.
Show solution
void main() {
const age = 15;
if (age >= 18) {
print('adult');
} else if (age >= 13) {
print('teen');
} else {
print('child');
}
}
teen