Search⌘ K
AI Features

The If, Else, and Else If Statements

Explore how to use if, else, and else if statements to manage decision-making in Dart programs. Learn chaining conditions, nesting statements, and simplifying code with the ternary operator to write clear and maintainable control flows.

When you wake up and check the weather, your decision to take an umbrella depends on whether it is raining. If it is raining, you take an umbrella. If it is not raining, you do nothing and leave. Conditional statements work the same way. They take the state of the program into consideration and act accordingly.

Executing code on a single condition

We use the if statement when we want a specific block of code to run only when a certain requirement is met.

The structure of an if statement consists of the if keyword followed by parentheses. We place our condition inside these parentheses. This condition must evaluate to a bool (true or false). We follow this with a block of code enclosed in curly braces.

Dart
if (condition) {
// Code to execute if the condition is true
}

Let us apply this to the weather scenario discussed earlier. We want to write a program that reminds us to take an umbrella, but only if it is currently raining.

Dart
void main() {
final isRaining = true;
if (isRaining) {
print('Take an umbrella!');
}
}
  • Line 2: We declare a boolean variable to represent the current weather state.

  • Line 4: We evaluate the isRaining variable. This resolves to a boolean value of true.

  • Line 5: We print a reminder to the console. The program runs this line specifically because the condition evaluates to true.

Providing a fallback using the else statement

The if statement handles a single condition and a single outcome. We often need two different actions depending on the result of a ...