Logical Operators
We can use logical operators to invert or combine two or more boolean expressions. In the following table, we can see the logical operators in Dart:
| Name | Operator | Description |
|---|---|---|
| Not | !a | Invert the value of a. Example: true will become false |
| Or | a || b | Combine two boolean expressions. If one of them is true then returns true |
| And | a && b | Combine two boolean expressions. If one of them is false then returns false |
Not: !
The not operator (a!) invert the variable's value. If it's true, then will become false. Example:
var a = true;
print(a); // prints true
print(!a); // prints false
And: &&
The and operator ( && ) combines two boolean expressions. If one is false, it evaluates to false. If both
are true, it evaluates to true. Example:
final alice = 25;
final rebecca = 16;
if (alice >= 18 && rebecca >= 18) {
print('Alice and Rebecca are 18 or more years old');
} else {
print('Alice and/or Rebecca are less then 18 years old');
}
The previous code will print Alice and/or Rebecca are less than 18 years old because Rebecca is younger than 18, so
the and operator returned false, and the code inside the else was executed.
OR: ||
The or operator ( || ) combines two boolean expressions. If one is true, it evaluates to true. If both
are false, it evaluates to false. Example:
final alice = 25;
final rebecca = 16;
if (alice >= 18 || rebecca >= 18) {
print('Alice or Rebecca are 18 or more years old');
} else {
print('Alice and Rebecca are less then 18 years old');
}
The previous code will print Alice or Rebecca are 18 or more years old because Alice is older than 18, so
the or operator returned true, and the code inside the if was executed.
Let's run the previous examples in DartPad: