Dart Logical Operators
Dart Logical Operators
Logical operators are used to combine true and false values.
They only work with bool values, and the result is also a bool.
| Operator | Name | Description | Example |
|---|---|---|---|
&& | Logical and | Returns true if both values are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the values is true | x < 5 || x < 4 |
! | Logical not | Reverses the result, true becomes false | !(x < 5) |
The && Operator
The && (and) operator returns true only if both sides are true:
Example
void main() {
int age = 25;
bool hasTicket = true;
print(age >= 18 && hasTicket);
print(age >= 30 && hasTicket);
}
Try it Yourself »
Result:
true
false
The || Operator
The || (or) operator returns true if at least one side is true:
Example
void main() {
bool isWeekend = false;
bool isHoliday = true;
print(isWeekend || isHoliday);
print(isWeekend || false);
}
Try it Yourself »
Result:
true
false
The ! Operator
The ! (not) operator turns true into false, and false into true:
Example
void main() {
bool isRaining = true;
print(!isRaining);
print(!(5 > 3));
}
Try it Yourself »
Result:
false
false
You can combine all three operators.
Use parentheses to make the order clear:
Example
void main() {
int temperature = 22;
bool isRaining = false;
bool goOutside = (temperature > 15 && temperature < 30) && !isRaining;
print(goOutside);
}
Try it Yourself »
Result:
true
Short-circuit Evaluation
Dart reads a logical expression from left to right, and it stops as soon as it knows the result.
This is called short-circuit evaluation.
- With
&&, if the left side isfalse, the right side is not checked - With
||, if the left side istrue, the right side is not checked
This is useful with nullable values.
In this example, age > 18 is only checked when age is not null:
Example
void main() {
int? age = int.tryParse('abc');
print(age != null && age > 18);
int? age2 = int.tryParse('42');
print(age2 != null && age2 > 18);
}
Try it Yourself »
Result:
false
true