简体   繁体   中英

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

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

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);
}

您可以在列表中使用compareTo方法根据这些结果比较结果您可以使用.sort方法对列表进行排序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM