Conditional Statements#
Conditional statements in Dart allow you to execute different blocks of code based on certain conditions. Here’s a breakdown of the main types of conditional statements:
if
Statement#
The if
statement executes a block of code if its condition evaluates to true
.
How It Works#
- Evaluates the condition inside the parentheses.
- If the condition is
true
, the code inside the block executes.
Usage#
Use if
statements to run specific code only when certain conditions are met.
Example#
int number = 10;
if (number > 0) {
print('The number is positive.');
}
In this example, the message “The number is positive.” will be printed only if number is greater than 0.
else Statement The else statement provides an alternative block of code that executes when the if condition evaluates to false.
How It Works If the if condition is false, the code inside the else block executes. Usage Use else to define a block of code to run when the if condition is not met.
Example#
int number = -5;
if (number > 0) {
print('The number is positive.');
} else {
print('The number is not positive.');
}
Here, the message “The number is not positive.” will be printed because number is less than or equal to 0.
else if Statement The else if statement allows you to test multiple conditions sequentially.
How It Works Evaluates the if condition first. If itβs false, evaluates the else if condition. Executes the block of code corresponding to the first true condition. Usage Use else if to handle multiple conditions that require different outcomes.
Example#
int number = 0;
if (number > 0) {
print('The number is positive.');
} else if (number < 0) {
print('The number is negative.');
} else {
print('The number is zero.');
}
in this example, “The number is zero.” will be printed because number is neither greater than nor less than 0.