How to sort a List of items based on dateTime in Flutter | Flutter

Issue

I have List of products with product name and date. I want to sort that list of items based on date and time. This is the list of items that i want to sort,

List items = [
    {
      "productName":"Icecream",
      "date":"2019-10-17 10:06:12.278"
    },
    {
      "productName":"Juice",
      "date":"2021-09-20 19:08:16.274"
    },
    {
      "productName":"Rice",
      "date":"2020-05-13 08:02:16.177"
    },
    {
      "productName":"Cheese",
      "date":"2021-10-23 20:02:16.254"
    },
    {
      "productName":"Sugar",
      "date":"2019-11-22 00:00:00.000"
    },
  ];

This is the Expected Output what i want,

List sortedList = [
    {
      "productName":"Icecream",
      "date":"2019-10-17 10:06:12.278"
    },
    {
      "productName":"Sugar",
      "date":"2019-11-22 00:00:00.000"
    },
    {
      "productName":"Rice",
      "date":"2020-05-13 08:02:16.177"
    },
    {
      "productName":"Juice",
      "date":"2021-09-20 19:08:16.274"
    },
    {
      "productName":"Cheese",
      "date":"2021-10-23 20:02:16.254"
    },
  ];

Solution

This is a simple code using the build-in function .compareTo that can help you out:

void main() async {
  List items = [
    {"productName": "Icecream", "date": "2019-10-17 10:06:12.278"},
    {"productName": "Juice", "date": "2021-09-20 19:08:16.274"},
    {"productName": "Rice", "date": "2020-05-13 08:02:16.177"},
    {"productName": "Cheese", "date": "2021-10-23 20:02:16.254"},
    {"productName": "Sugar", "date": "2019-11-22 00:00:00.000"},
  ];

  // You can change the position of `a` and `b` to get a reversed result
  // as well
  items.sort((a, b) => a['date'].compareTo(b['date']));

  print(items);
}

Answered By – Softs.dev

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

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