Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example
Comparison operators (<,>,>=,<=,==
) are useful to compare the values.
Enum contains constant values that represent the index starting from 0,1 onwards.
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Enum Week
contains constants such as MONDAY
and index
is 0, the second value is TUESDAY
and index
is 1.
By default, two enum objects are equal using the == operator.
void main() {
WEEK sat = WEEK.SATURDAY;
WEEK mon = WEEK.MONDAY;
print(sat == mon); //true
}
Let’s see a comparison operator such as <
or >
.
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
void main() {
WEEK sat = WEEK.SATURDAY;
WEEK mon = WEEK.MONDAY;
print(sat < mon); //throws an error
}
Output:
**Error: The operator '<' isn't defined for the class 'WEEK'.
'WEEK' is from 'package:dartpad_sample/main.dart' ('lib/main.dart').
print(sat < mon); //throws an error**
Dart Comparision Operator Examples
Enum provides compareByIndex
that compares the values by their index.
int compareByIndex<T extends Enum>(
T value1,
T value2
)
It returns an int value.
Here is a dart enum compareByIndex example
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
void main() {
print(Enum.compareByIndex(WEEK.SUNDAY, WEEK.MONDAY)); // 6
print(Enum.compareByIndex(WEEK.MONDAY, WEEK.MONDAY)); // 0
print(Enum.compareByIndex(WEEK.MONDAY, WEEK.SUNDAY)); //-6
}
You can also add an extension method to Enum constants in Dart.
When you are defining an extension method as an operator, the keyword operator must be added before an operator.
Otherwise, throws an error Error: Operator declarations must be preceded by the keyword ‘operator’.
Here is a Dart Enum Comparision operator example
enum WEEK { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
extension EnumOperators on WEEK {
bool operator >(WEEK current) {
return index > current.index;
}
bool operator >=(WEEK current) {
return index >= current.index;
}
bool operator <(WEEK current) {
return index < current.index;
}
bool operator <=(WEEK current) {
return index <= current.index;
}
}
void main() {
print(WEEK.SUNDAY < WEEK.MONDAY); // false
print(WEEK.MONDAY > WEEK.MONDAY); // false
print(WEEK.MONDAY <= WEEK.SUNDAY); // true
}
Conclusion
By default, the double equal(==
) operator works with Enum objects in dart.Method Dart Enum.compareByIndex
returns an index that compares with the operator.
Enum Comparision operators work by adding an extension operator.