In Dart, conditional statements are used to control the flow of execution based on specified conditions. There are several types of conditional statements available in Dart:
if
statement:
The if
statement is used to execute a block of code if a specified condition is true. It can be followed by an optional else
statement to execute a different block of code when the condition is false.
int age = 18;
if (age >= 18) {
print("You are an adult.");
} else {
print("You are not an adult yet.");
}
else if
statement:
The else if
statement allows you to specify additional conditions to be checked if the preceding if
statement or else if
statements evaluate to false.
int marks = 75;
if (marks >= 90) {
print("Grade: A");
} else if (marks >= 80) {
print("Grade: B");
} else if (marks >= 70) {
print("Grade: C");
} else {
print("Grade: D");
}
Ternary operator:
The ternary operator (? :
) is a concise way to express a conditional expression. It evaluates a condition and returns one of two expressions based on the result.
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
print(status); // Output: Adult
switch
statement :
this is used to select one of many code blocks to be executed based on the value of an expression. It provides an alternative to using multiple if
statements when checking for different possible values of a variable. Here’s an example of how to use the switch
statement in Dart:
String color = "red";
switch (color) {
case "red":
print("The color is red.");
break;
case "blue":
print("The color is blue.");
break;
case "green":
print("The color is green.");
break;
default:
print("Unknown color.");
}
These conditional statements in Dart allow you to make decisions based on specific conditions, enabling your program to adapt and respond dynamically. By utilizing if
statements, else if
statements, and the ternary operator, you can control the flow of execution based on the values and conditions in your code.