In Dart, conditional statements and logical operators are used to execute code based on certain conditions.
Conditional Statements
Conditional statements allow you to execute a block of code only if a specified condition is true. Dart has two types of conditional statements: if-else and switch-case.
If-else Statement
The if-else statement is used to execute a block of code if a certain condition is true, and another block of code if the condition is false. The basic syntax of the if-else statement is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
For example, the following code will print “Positive” if the variable x
is positive, and “Negative” if ‘ x
‘ is negative:
void main() {
int x = 10;
if (x > 0) {
print("Positive");
} else {
print("Negative");
}
}
Switch-case Statement
The switch-case statement is used to execute a block of code based on multiple conditions. The basic syntax of the switch-case statement is as follows:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
...
default:
// code to be executed if no case matches the expression
break;
}
For example, the following code will print “Monday” if the variable day
is 1, “Tuesday” if day
is 2, and so on:
void main() {
int day = 1;
switch (day) {
case 1:
print("Monday");
break;
case 2:
print("Tuesday");
break;
case 3:
print("Wednesday");
break;
...
default:
print("Invalid day");
break;
}
}
Logical Operators
Dart supports the following logical operators:
&&
(and) – returns true
if both operands are true
, false
otherwise.
bool result = true && true; // result = true
||
(or) – returns true
if at least one operand is true
, false
otherwise.
bool result = !false; // result = true
!
(not) – returns the negation of a boolean expression.
bool result = !false; // result = true
Note that in Dart, non-boolean values can be used in logical expressions, but they will be implicitly converted to booleans using the following rules:
null
is equivalent tofalse
- Other values (e.g.
0
,''
) are equivalent totrue
bool result = '' && false; // result = false
Examples:
Checking user input
String username = 'admin';
String password = 'password';
if (username == 'admin' && password == 'password') {
print('Access granted');
} else {
print('Access denied');
}
Making a decision based on multiple conditions
String status = 'approved';
int score = 80;
if (status == 'approved' || score >= 90) {
print('Eligible for a bonus');
} else {
print('Not eligible for a bonus');
}
Average Rating