Dart List.sortedBy function with generic Comparable as parameter wont manipulate the list

Viewed 170

I want to order objects in a List by the value of the objects instance variables and i actually found exactly what I was looking for in this post: https://stackoverflow.com/a/62008660/4420202 ...and this post: https://stackoverflow.com/a/60920035/4420202 but no mather what my lists objects stays in the exact same order.

This is the extension:

extension MyIterable<E> on Iterable<E> {
  Iterable<E> sortedBy(Comparable key(E e)) =>
      toList()..sort((a, b) => key(a).compareTo(key(b)));
}

And this is how i use it:

list.sortedBy((it) => it.name);

Any help would be much appreciated. Thanks

1 Answers

It doesn't order the list itself. It returns a new iterable with all elements in order. Save it into a variable and then you can then iterate over that to get the all elements in order. If you want the result as a list you can use the toList method.

Related