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
}
We declare a variable
age
and initialize it with the value20
.We declare a Boolean variable
isStudent
and initialize it with the valuefalse
.We start an
if
statement with the conditionage >= 18
. This checks if theage
is greater than or equal to18
.If the condition
age >= 18
is true, we enter the block of code associated with the outerif
statement.Inside the block of code for the outer
if
statement, we have anotherif-else
statement.The inner
if-else
statement checks the value ofisStudent
. IfisStudent
istrue
, it prints "You are eligible for a student discount.". Otherwise, it prints "You are eligible to vote.".If the condition
age >= 18
is false, we skip the block of code associated with the outerif
statement and move to theelse
block. Here, we print "You are not eligible to vote yet.".