Syntax
Use else if to test multiple conditions in sequence. Dart evaluates them top-to-bottom and executes the first matching block:
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition2 is true
} else if (condition3) {
// runs if condition3 is true
} else {
// runs if none of the above are true
}
Example
void main() {
int score = 72;
String grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
print('Score: $score → Grade: $grade');
// BMI classifier
double bmi = 22.5;
if (bmi < 18.5) {
print('Underweight');
} else if (bmi < 25.0) {
print('Normal weight');
} else if (bmi < 30.0) {
print('Overweight');
} else {
print('Obese');
}
}
Output:Score: 72 → Grade: C
Normal weight
📝 Note: Once a matching condition is found, the rest of the chain is skipped — even if later conditions would also be true.
💪 Exercise
- Write a program that classifies a number as negative, zero, or positive.
- Build a traffic light interpreter: given "red", "yellow", or "green", print the appropriate instruction.
- Write a grade calculator for 5 grade levels (A, B, C, D, F).
🧠 Quiz
1. How many else-if blocks can you chain?
- A) Maximum 3
- B) Maximum 5
- C) Unlimited ✅
- D) Maximum 10
2. If condition1 and condition2 are both true, which block executes?
- A) Both blocks
- B) The condition1 block ✅
- C) The condition2 block
- D) Neither
Summary
Use else if to chain multiple conditions. Dart evaluates them top-to-bottom and executes only the first matching block. An optional final else handles the case when no condition matches.