
If Else and Ternary Operator in Dart
29 March, 2023
1
1
0
Contributors
If Else
In the Dart programming language, the if
and else
statements are used to control the flow of execution in a program based on a specified condition. These statements allow a programmer to specify a block of code to be executed if a certain condition is true, and another block of code to be executed if the condition is false.
Syntax
The syntax for an if
statement in Dart is as follows:
if (condition) {
// code to be executed if condition is true
}
An if
statement can also include an else
clause, which specifies a block of code to be executed if the condition is false:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
Here is an example of an if
statement in Dart that checks whether a variable x
is greater than 10:
int x = 15;
if (x > 10) {
print("x is greater than 10");
} else {
print("x is not greater than 10");
}
This code would output "x is greater than 10" to the console.
Nested if
statements
It is also possible to nest if
statements inside of each other. For example:
int x = 15;
int y = 20;
if (x > 10) {
if (y > 15) {
print("x is greater than 10 and y is greater than 15");
} else {
print("x is greater than 10 and y is not greater than 15");
}
} else {
print("x is not greater than 10");
}
In this example, the inner if
statement will only be executed if the outer if
statement's condition is true.
Ternary operator
The ternary operator (? :
) can be used as a shorthand version of an if
statement. The syntax for the ternary operator is as follows:
condition ? expression1 : expression2
If the condition
is true, the expression expression1
will be evaluated. If the condition is false, the expression expression2
will be evaluated.
Here is an example of the ternary operator being used in place of an if
statement:
int x = 15;
int y = 20;
int max = x > y ? x : y;
print("The maximum value is $max");
This code would output "The maximum value is 20" to the console.
In conclusion, the if
and else
statements are an essential part of control flow in the Dart programming language. They allow a programmer to specify different blocks of code to be executed based on a given condition, and can be used in a variety of situations to control the flow of execution in a program.