Dart If Else Statement
In Dart, an if-else statement selects one of two code blocks based on a Boolean condition. Dart executes the if block when the condition is true; otherwise, it executes the else block.
Use an if-else statement when a program must choose between two mutually exclusive actions, such as displaying whether a number is even or odd, checking whether a user is eligible, or selecting a message based on a result.
How Dart If-Else Selects a Code Block
A Dart if-else statement contains an if block, a Boolean condition, and an else block.
- If the condition evaluates to
true, Dart executes the statements inside theifblock and skips theelseblock. - If the condition evaluates to
false, Dart skips theifblock and executes the statements inside theelseblock. - Only one of the two blocks runs for each evaluation of the statement.
Dart If-Else Syntax
The syntax of if-else statement in Dart is given in the following.
if (boolean_expression) {
//if block statement(s)
} else {
//else block statement(s)
}
The boolean_expression must have the type bool and evaluate to either true or false. Unlike some programming languages, Dart does not treat integers, strings, or other objects as implicit Boolean values.
For example, if (1) and if (name) are invalid in Dart. Write an explicit condition such as if (count > 0) or if (name.isNotEmpty).
Dart If-Else Example for an Even or Odd Number
In the following program, we take an integer value in x, and check if the number in x is even or odd using if-else statement.
main.dart
void main(){
int x = 13;
if(x%2==0){
print('$x is even number.');
} else{
print('$x is odd number.');
}
}
Output
13 is odd number.
The expression x % 2 == 0 checks the remainder after dividing x by 2. For x = 13, the remainder is 1, so the condition is false and Dart executes the else block.
Dart If-Else Example with a Comparison Condition
The following example checks whether a score meets a specified passing value.
void main() {
int score = 72;
if (score >= 40) {
print('You passed the exam.');
} else {
print('You did not pass the exam.');
}
}
Output
You passed the exam.
Since 72 >= 40 evaluates to true, Dart executes the first block. Changing score to a value below 40 would cause the else block to run.
Using Logical Operators in a Dart If-Else Condition
A condition can combine multiple Boolean expressions with Dart logical operators. The commonly used operators are && for logical AND, || for logical OR, and ! for logical NOT.
void main() {
int age = 22;
bool hasId = true;
if (age >= 18 && hasId) {
print('Entry allowed.');
} else {
print('Entry denied.');
}
}
Output
Entry allowed.
Both expressions must be true because they are connected with &&. Dart uses short-circuit evaluation, so it does not evaluate the second expression when the first expression already determines the result.
Dart If-Else with a Boolean Variable
When a variable already has the type bool, it can be used directly as the condition.
void main() {
bool isLoggedIn = false;
if (isLoggedIn) {
print('Welcome back.');
} else {
print('Please sign in.');
}
}
Output
Please sign in.
Writing if (isLoggedIn) is clearer than comparing the variable with true. Similarly, use if (!isLoggedIn) when the block should run for a false Boolean value.
Using Else-If for More Than Two Dart Conditions
A basic if-else statement chooses between two paths. When a program must test several conditions in order, add one or more else if branches before the final else.
void main() {
int temperature = 28;
if (temperature >= 35) {
print('Hot');
} else if (temperature >= 20) {
print('Moderate');
} else {
print('Cold');
}
}
Output
Moderate
Dart evaluates the conditions from top to bottom and executes the first matching branch. It then skips the remaining branches. Arrange overlapping conditions from the most restrictive to the least restrictive so that an earlier condition does not capture values intended for a later branch.
Nested If-Else Statements in Dart
An if-else statement can appear inside another conditional block. This is called nesting and is useful when a second decision depends on the result of the first decision.
void main() {
int number = 8;
if (number > 0) {
if (number % 2 == 0) {
print('Positive even number');
} else {
print('Positive odd number');
}
} else {
print('The number is zero or negative');
}
}
Output
Positive even number
Use nesting only when the second condition genuinely depends on the first. Deeply nested blocks can be difficult to read and may be clearer when rewritten with an else if chain, an early return, or a separate function.
Dart If-Else and the Conditional Operator
For a short choice between two values, Dart also supports the conditional operator condition ? valueIfTrue : valueIfFalse. It produces a value, whereas an if-else statement controls which statements are executed.
void main() {
int number = 7;
String result = number % 2 == 0 ? 'even' : 'odd';
print('$number is $result.');
}
Output
7 is odd.
Use the conditional operator for a compact value selection. Prefer a regular if-else statement when either branch contains several statements or when the shorter form would make the code harder to understand.
Common Dart If-Else Mistakes
Using a Non-Boolean If Condition
Dart requires a bool condition. A number or string cannot be used as an implicit true or false value.
void main() {
int count = 3;
if (count > 0) {
print('Items are available.');
} else {
print('No items are available.');
}
}
Confusing Assignment with Equality
Use == to compare values. The single equals sign = assigns a value to a variable and is not an equality comparison.
Adding a Semicolon After the If Condition
Do not place a semicolon immediately after the closing parenthesis of an if condition. It creates an empty statement and prevents the following block from working as intended.
Writing Overlapping Else-If Conditions in the Wrong Order
In an else-if chain, Dart stops at the first true condition. Test narrower ranges before broader ranges. For example, check score >= 90 before score >= 40.
Dart If-Else FAQs
Does a Dart if condition have to be Boolean?
Yes. The condition must evaluate to a value of type bool. Dart does not automatically convert numbers, strings, lists, or objects to true or false.
Is the else block required in Dart?
No. Use a standalone if statement when code should run only for a true condition and no alternative action is required. Add else when the false case also needs a code block.
Can a Dart if-else statement contain multiple conditions?
Yes. Combine Boolean expressions with && or ||, or use an else if chain to evaluate several alternatives in order.
What is the difference between else-if and nested if in Dart?
An else-if chain chooses the first matching branch from several alternatives. A nested if performs another conditional check inside a branch that has already been selected.
Dart If-Else Editorial QA Checklist
- Confirm that every condition in the Dart examples evaluates to a
boolvalue. - Verify that the even-or-odd example uses the remainder expression
x % 2 == 0correctly. - Check that each displayed output matches the values assigned in its corresponding Dart program.
- Confirm that narrower conditions appear before broader conditions in every else-if chain.
- Ensure that examples use braces consistently and do not contain a semicolon immediately after an
ifcondition.
Dart If-Else Summary
A Dart if-else statement evaluates a Boolean condition and executes exactly one of two code blocks. Use comparison and logical operators to construct conditions, use else if for multiple alternatives, and use the conditional operator only when selecting between two simple values.
In this Dart Tutorial, we learned the syntax and usage of Dart Conditional Statement: If-Else.
TutorialKart.com