Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort object by int in dart

The package collection use something similar to the following code but I don’t know why it does not work with it integers and double. But It works with string, duration, datetimes.

extension ListExtensionSort<T> on List<T> {
  void sortByDescOrder<K extends Comparable<K>>(K Function(T element) keyOf,
      [int start = 0, int? end]) {
    sort((b, a) => keyOf(a).compareTo(keyOf(b)));
  }
}
void main() {
  List<Person> people = [
    Person('Alice', 30),
    Person('Bob', 25),
    Person('Charlie', 35),
  ];

  (24).compareTo(56);
  // Sort by age in ascending order
  people.sortByDescOrder((person) => person.age); // does not work
  people.sortByDescOrder((person) => person.name); // does work

  // Print sorted list
  people.forEach((person) {
    print('${person.name}: ${person.age}');
  });
}

Couldn’t infer type parameter ‘K’. Tried to infer ‘int’ for ‘K’ which
doesn’t work: Type parameter ‘K’ is declared to extend ‘Comparable’
producing ‘Comparable’. The type ‘int’ was inferred from:
Parameter ‘keyOf’ declared as ‘K Function(Person)’ but argument is
‘int Function(Person)’.

Update:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I found an overly ugly solution

 people.sortByDescOrder((person) {
    num age = person.age;
    return age;
  });

>Solution :

The issue is that neither int nor double directly implement the Comparable interface. They both extend num which indeed impements the Comparable<num> interface.

This means that while it correctly infers the type for K as int it does not adhere to the bounds of Comparable<int>

There is actually an open issue about this here: https://github.com/dart-lang/sdk/issues/43763

To work around the issue you can just provide the generic type yourself:

people.sortByDescOrder<num>((person) => person.age);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading