如何在 Flutter 中根据日期时间对项目列表进行排序 |扑

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

我有带有产品名称和日期的产品列表。我想根据日期和时间对该项目列表进行排序。这是我要排序的项目列表,

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

这是我想要的预期输出,

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

这是一个使用内置函数 .compareTo 的简单代码,可以帮助您:

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 方法对列表进行排序