Syntax
An if-else block runs one of two code blocks depending on whether the condition is true or false:
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
Example
void main() {
int age = 16;
if (age >= 18) {
print('You are an adult.');
} else {
print('You are a minor.');
}
double temperature = 15.0;
if (temperature >= 20) {
print('Wear a t-shirt.');
} else {
print('Wear a jacket.');
}
int number = 7;
if (number % 2 == 0) {
print('$number is even.');
} else {
print('$number is odd.');
}
}
Output:You are a minor.
Wear a jacket.
7 is odd.
⚠️ Common Mistakes
- Adding a semicolon after
if(condition) — this creates an empty if block.
- Using
= instead of == in the condition: if (x = 5) is a compile error in Dart.
💪 Exercise
- Write a program to check if a year is a leap year (divisible by 4, with special cases for 100 and 400).
- Check if a number is positive or negative or zero (hint: use if-else-if from the next lesson for zero).
- Check if a student passed an exam (score >= 50).
🧠 Quiz
1. When does the else block execute?
- A) Always
- B) When the if condition is true
- C) When the if condition is false ✅
- D) Never
Summary
The if-else statement provides two execution paths. If the condition is true, the if block runs; otherwise the else block runs. Exactly one of the two blocks always executes.