Navigating Dart Space: Overview of Conditional Statements in Dart

Greetings, fellow Dart Astronaut! Today, we are going to explore an integral part of programming: conditional statements. Such statements determine the course of our program. Are you prepared to delve into the if-else, switch case, and the nimble yet powerful ternary operator in Dart? Fasten your seatbelt!

Dart If and If-Else Structure

The if and if-else blocks in Dart are structured as follows:

if (condition) {
    // action if the condition is true
}

// and

if (condition) {
    // action if the condition is true
} else {
    // action if the condition is false
}

When the provided condition is true, the if block gets executed. On the other hand, when the condition is false, the else block, if present, gets the go-ahead.

Probing the Universe with Dart If-Else Statement

The if statement in Dart guides the computer to perform specific actions under particular conditions. Let's simulate an encounter with a planet offering breathable air:

int oxygenLevel = 78; // The oxygen level on the planet

if (oxygenLevel > 20) {
    print("Planet has breathable air!"); // Oxygen level is fine
} else {
    print("Oxygen level is too low!"); // Oxygen level is inadequate
}
// The code prints: Planet has breathable air!

In this example, the statement if (oxygenLevel > 20) verifies whether the oxygen level surpasses 20. If the condition holds true, it prints: "Planet has breathable air!". Conversely, if it is false, else guides us to an alternate command that prints: "Oxygen level too low!".

Dart Else If Statement: Tackling Multiple Conditions

To handle multiple conditions, we can employ else if:

int oxygenLevel = 58;
if (oxygenLevel > 70) {
    print("Excellent Oxygen level!");
} else if (oxygenLevel > 50) {
    print("Oxygen level is acceptable.");
} else {
    print("Oxygen level is too low!");
}
// The code prints: Oxygen level is acceptable.

The else if keyword offers multiple paths for the program to follow until a fitting one is located. Once a condition is met, the program disregards all remaining else if conditions.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal