Dart Control flow: if-else Statement | Nested if-else Statements

Dart Control flow: if-else Statement | Nested if-else Statements

In Dart, control flow statements like if-else are crucial for managing the execution flow of your code. Let's explore the if-else statement and nested if-else statements in Dart:

If-else Statement:

The if-else statement is used to execute one block of code if a condition is true and another block if the condition is false.

Nested if-else Statement:

Nested if-else statements are if-else statements inside another if or else block. They allow you to further refine the decision-making process based on additional conditions.

Here's the basic syntax:

if (condition1) {
  // Code to execute if condition1 is true
  if (condition2) {
    // Code to execute if both condition1 and condition2 are true
  } else {
    // Code to execute if condition1 is true but condition2 is false
  }
} else {
  // Code to execute if condition1 is false
}

  1. We declare a variable age and initialize it with the value 20.

  2. We declare a Boolean variable isStudent and initialize it with the value false.

  3. We start an if statement with the condition age >= 18. This checks if the age is greater than or equal to 18.

  4. If the condition age >= 18 is true, we enter the block of code associated with the outer if statement.

  5. Inside the block of code for the outer if statement, we have another if-else statement.

  6. The inner if-else statement checks the value of isStudent. If isStudent is true, it prints "You are eligible for a student discount.". Otherwise, it prints "You are eligible to vote.".

  7. If the condition age >= 18 is false, we skip the block of code associated with the outer if statement and move to the else block. Here, we print "You are not eligible to vote yet.".