What is an If Statement?
An if statement executes a block of code only when a condition is true. It is the most fundamental control flow tool in Dart.
Syntax
if (condition) {
// code runs when condition is true
}
Example
void main() {
int temperature = 35;
if (temperature > 30) {
print('It is hot outside!');
}
int score = 85;
if (score >= 60) {
print('You passed the exam.');
}
bool isRaining = false;
if (!isRaining) {
print('No need for an umbrella.');
}
}
Output:It is hot outside!
You passed the exam.
No need for an umbrella.
If the condition is false, the block is simply skipped — no error occurs.
📝 Note: The condition inside if() must evaluate to a bool. Dart does not accept non-boolean expressions like if (1) or if ("text").
💪 Exercise
- Write a program that prints "Teenager" if age is between 13 and 19.
- Check if a number is positive and print a message.
- Check if a string is empty and print an appropriate message.
🧠 Quiz
1. What happens if an if condition is false?
- A) Error is thrown
- B) The block is skipped ✅
- C) Program stops
- D) null is returned
2. Which type must the if condition evaluate to?
- A) int
- B) String
- C) bool ✅
- D) Any type
Summary
The if statement runs a block of code only when its boolean condition is true. If the condition is false, the block is skipped. Always use a proper boolean expression — Dart does not support truthy/falsy non-boolean values in conditions.