How to sort a MappedListIterable in Dart

Issue

I’ve got a MappedListIterable than I know to sort

When calling the sort method , I ‘m getting

EXCEPTION: NoSuchMethodError: Class ‘MappedListIterable’ has no
instance method ‘sort’. Receiver: Instance of ‘MappedListIterable’
Tried calling: sort(Closure: (dynamic, dynamic) => dynamic)

Solution

You get a MappedListIterable after calling .map(f) on an Iterable.

The Iterable class does not have a sort() method. This method is on List.

So you first need to get a List from your MappedListIterable by calling .toList() for example.

var i = [1, 3, 2].map((i) => i + 1);
// i is a MappedListIterable
// you can not call i.sort(...)

var l = i.toList();
l.sort(); // works

Or in one line (code-golf):

var i = [1, 3, 2].map((i) => i + 1).toList()..sort();

Answered By – Alexandre Ardhuin

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *