I have a list of maps in dart that I would like to sort.

The list I use:

List<myModel> myList; 

(with maps inside):

(I created a model called 'myModel', so if I want to get the views: so I can use: myList[index].views to get the views of a map).

I tried this code:

setState(() {
        filteredList = SplayTreeMap.from(
            myList,
            (a, b) => int.parse(myList[a].views)
                .compareTo(int.parse(myList[b].views)));
      });

(I want to sort the views, hight to low).

But I get this error:

error: A value of type 'SplayTreeMap' can't be assigned to a variable of type 'List<myModel>'.

What am I doing wrong?

Thanks in advance!

EDIT:

I 'query' my list this way.

    filteredList = myList
        .where((snapshot) => snapshot.views > 0)
        .toList();

This works...

Is there a possibility to sort that way?


Solution 1: voracious

You cannot pass a List to SplayTreeMap.from(...).

See the documentation:

SplayTreeMap.from(Map other, [int compare(K key1 K key2), bool isValidKey(dynamic potentialKey)])

You need to use a Map or otherwise use SplayTreeMap.fromIterable(...) (documentation):

SplayTreeMap.fromIterable(Iterable iterable, {K key(dynamic element), V value(dynamic element), int compare(K key1 K key2), bool isValidKey(dynamic potentialKey)})

You could implement in the following way:

final filteredList = 
    SplayTreeMap.fromIterable(
      myList,
      key: (m) => m,
      value: (m) => m.views,
      compare: (a, b) => 
        int.parse(a.views).compareTo(int.parse(b.views))
    );

The above is an example, adjust it to your needs.

EDIT 2:
Given your edit, you could do something like:

final temp = List.from(myList);
temp.sort((a, b) => int.parse(a.views).compareTo(int.parse(b.views)));

filteredList = temp;