by @kodeazy

What is comparator in flutter,dart and how it works with an example?

Home » flutter » What is comparator in flutter,dart and how it works with an example?
  • Comparator is used to order similar types of Objects.
  • With the help of Comparator we can sort the user defined class objects.
  • For example we have a class ComparatorEmployee.

    class ComparatorEmployee {
    int age;
    int salary;
    String name;
    ComparatorEmployee(int this.age, int this.salary, String this.name) {
    this.age = age;
    this.salary = salary;
    this.name = name;
    }
    }
  • Here we create objects of user defined class ComparatorEmployee and add them to List.

    ComparatorEmployee employeesList1 = new ComparatorEmployee(27, 103, "Suresh");
    ComparatorEmployee employeesList2 = new ComparatorEmployee(23, 102, "Ramesh");
    ComparatorEmployee employeesList3 = new ComparatorEmployee(21, 105, "Mahesh");
    ComparatorEmployee employeesList4 = new ComparatorEmployee(29, 104, "Gopi");
    
    List<ComparatorEmployee> employeesList = [
    employeesList1,
    employeesList2,
    employeesList3,
    employeesList4
    ];
  • Here employeesList1,employeesList2,employeesList3,employeesList4 are the Objects assigned to List.

    Comparator<ComparatorEmployee> employeSalary =
      (x, y) => x.salary.compareTo(y.salary);
    employeesList.sort(employeSalary);
  • To sort the objects based on Salary of the employee here we use compareTo() method and used salary as attribute. it returns negitive,positive, zero values, based on these values objects are swapped.
  • Here sort() method is used to sort Objects based on attributes provided in compareTo() method.
  • Below is a complete example of how to sort user defined employee objects based on salary.
class ComparatorEmployee {
  int age;
  int salary;
  String name;
  ComparatorEmployee(int this.age, int this.salary, String this.name) {
    this.age = age;
    this.salary = salary;
    this.name = name;
  }
}



void main() {
    
  ComparatorEmployee employeesList1 = new ComparatorEmployee(27, 103, "Suresh");
  ComparatorEmployee employeesList2 = new ComparatorEmployee(23, 102, "Ramesh");
  ComparatorEmployee employeesList3 = new ComparatorEmployee(21, 105, "Mahesh");
  ComparatorEmployee employeesList4 = new ComparatorEmployee(29, 104, "Gopi");
  List<ComparatorEmployee> employeesList = [
    employeesList1,
    employeesList2,
    employeesList3,
    employeesList4
  ];
  Comparator<ComparatorEmployee> employeSalary =
      (x, y) => x.salary.compareTo(y.salary);
  employeesList.sort(employeSalary);
  employeesList.forEach((ComparatorEmployee employeeDetails) {
    print(
        '${employeeDetails.age} - ${employeeDetails.name} - ${employeeDetails.salary}');
  });
}

Output:

23 - Ramesh - 102
27 - Suresh - 103
29 - Gopi - 104
21 - Mahesh - 105