Home > Back-end >  How to sort a list of maps based on values inside the maps in Dart?
How to sort a list of maps based on values inside the maps in Dart?

Time:11-09

I have a list that I want to sort. That list contains multiple maps with key and values. Basically, it looks like this:

class MyObject{
  DateTime date;
  String myText;

  MyObject({required this.date, required this.myText});
}

void main()
{
  MyObject obj1 = MyObject(date: DateTime.now(), myText: "abc");
  MyObject obj2 = MyObject(date: DateTime.now(), myText: "bcd");

  // just a demo, in reality there are more unordered dates
  var myList = [{"obj": obj1 , "etc": "someEntry1"}, {"obj": obj2, "etc": "someEntry2"}];
}

I want to sort the list based on ascending dates in the maps and tried the following line of code to sort the list:

myList.sort((a, b) => a['obj'].date.compareTo(b['obj'].date));

But I ended up getting the following error: enter image description here

How to solve the sorting problem? Thanks for your help!

CodePudding user response:

I couldn't replicate the exact same error. But you can make it sort, as I think you want, by making a small adjustment.

Since your map is mixing datatypes, then you have to help dart know that the object under the key "obj" is of type MyObject. Check this DartPad where I've added a cast.

This is what I've changed:

myList.sort((a, b) => (a['obj']! as MyObject).date.compareTo((b['obj']! as MyObject).date));

Note that you might want to do something safer than just assuming that x['obj'] will not be null...

  • Related