Understanding how to use the if else
statement in Dart is essential for beginners and developers working on conditional logic in Flutter or Dart-based applications. The if else
structure allows your program to make decisions based on conditions and respond differently depending on whether the condition evaluates to true
or false
.

What Is an If Else Statement in Dart?
The if else
statement in Dart is used to execute certain blocks of code based on whether a condition is true or false. Dart also supports else if
for checking multiple conditions in a structured way.
Syntax:
void main() {
int number = 10;
if (number > 0) {
print("The number is positive.");
} else if (number == 0) {
print("The number is zero.");
} else {
print("The number is negative.");
}
}
void main() {
int number = 10;
if (number > 0) {
print("The number is positive.");
} else if (number == 0) {
print("The number is zero.");
} else {
print("The number is negative.");
}
}
void main() { int number = 10; if (number > 0) { print("The number is positive."); } else if (number == 0) { print("The number is zero."); } else { print("The number is negative."); } }
In the example above:
- If
number > 0
, the program prints that the number is positive. - If the number is exactly
0
, it prints a different message. - If none of the above, it falls into the
else
clause.
Use Cases:
- Validating user input
- Controlling app navigation
- Handling dynamic UI changes
- Filtering data based on conditions
- Executing fallback logic
Best Practices:
- Always ensure conditions are clear and concise.
- Avoid deeply nested if-else blocks.
- Consider using
switch
if you have multiple discrete cases.
For further reading on Dart’s control flow, visit this official Dart language guide.