by @kodeazy
what is comparable in flutter,dart and how it works?
- comparable is an interface used to sort objects of user defined class.
sort()
method is used to sort the objects.-
For Example
List<ComparatorEmployee> al = [ ComparatorEmployee(27, 103, "Suresh"), ComparatorEmployee(23, 102, "Ramesh"), ComparatorEmployee(21, 105, "Mahesh"), ComparatorEmployee(29, 104, "Gopi") ];
- Here
al
is alist
which has collection ofObjects
. al.sort();
is used to sort these collection of Objects.-
compareTo(T other)
method Compares current object with the specified object for order to sort in ascending or descending order as per the requirment.int compareTo(ComparatorEmployee other) { if (age > other.age) { return 1; } else if (age < other.age) { return -1; } else return 0; }
compareTo(Object)
method returnspositive
ornegitive
orzero
as above.
- Above method returns
Objects
inAsc
order. - To print in
Desc
order just modify the method return statments from1 to-1
and-1 to 1
as below incompareTo(T other)
method.
int compareTo(ComparatorEmployee other) {
if (age > other.age) {
return -1;
} else if (age < other.age) {
return 1;
} else
return 0;
}
Below is the Example to Sort and display employees data based on their salary in Ascending Order
void main() {
List<ComparatorEmployee> al = [
ComparatorEmployee(27, 103, "Suresh"),
ComparatorEmployee(23, 102, "Ramesh"),
ComparatorEmployee(21, 105, "Mahesh"),
ComparatorEmployee(29, 104, "Gopi")
];
al.sort();
al.forEach((element) {
print(
'Name is ${element.name} Age is ${element.age} Salary is ${element.salary}');
});
}
class ComparatorEmployee implements Comparable<ComparatorEmployee> {
int age = 0;
int salary = 0;
String name = "";
ComparatorEmployee(int age, int salary, String name) {
this.age = age;
this.salary = salary;
this.name = name;
}
int compareTo(ComparatorEmployee other) {
if (age > other.age) {
return 1;
} else if (age < other.age) {
return -1;
} else
return 0;
}
}
Output:
Name is Mahesh Age is 21 Salary is 105
Name is Ramesh Age is 23 Salary is 102
Name is Suresh Age is 27 Salary is 103
Name is Gopi Age is 29 Salary is 104