1

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"
    },
  ];

1

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can use compareTo method in list to compare results based on these results you can sort list using .sort method on list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.