Dart Comparison Operators
Dart Comparison Operators
Comparison operators are used to compare two values.
The result of a comparison is always a bool, true or false.
| Operator | Name | Example |
|---|---|---|
== | Equal to | x == y |
!= | Not equal to | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Example
void main() {
int x = 5;
int y = 3;
print(x == y);
print(x != y);
print(x > y);
print(x < y);
print(x >= 5);
print(y <= 2);
}
Try it Yourself »
Result:
false
true
true
false
true
false
Using the Result
You can store the result of a comparison in a bool variable:
Example
void main() {
int age = 16;
bool canVote = age >= 18;
print('Can vote: $canVote');
}
Try it Yourself »
Result:
Can vote: false
Comparisons are most often used in if statements and loops.
You will learn about them in the If...Else chapter.
Comparing int and double
An int and a double with the same value are equal:
Example
void main() {
int a = 10;
double b = 10.0;
print(a == b);
print(a < 10.5);
}
Try it Yourself »
Result:
true
true
Comparing Strings
Use == and != to check if two strings are the same.
The comparison is case-sensitive, so 'Apple' and 'apple' are not equal:
Example
void main() {
String fruit = 'apple';
print(fruit == 'apple');
print(fruit == 'Apple');
print(fruit != 'banana');
}
Try it Yourself »
Result:
true
false
true
The operators <, >, <= and >= do not work with strings:
Result:
main.dart:2:17: Error: The operator '<' isn't defined for the type 'String'.
Try correcting the operator to an existing operator, or defining a '<' operator.
print('apple' < 'banana');
^
To find which string comes first in alphabetical order, use compareTo().
It returns a negative number if the first string comes first, 0 if they are equal, and a positive number if the first string comes after the second:
Example
void main() {
print('apple'.compareTo('banana'));
print('apple'.compareTo('apple'));
print('cherry'.compareTo('banana'));
}
Try it Yourself »
Result:
-1
0
1