【问题标题】:How to sort a List of items based on dateTime in Flutter | FlutterFlutter 中如何根据 dateTime 对 List 进行排序扑
【发布时间】:2021-12-09 19:49:13
【问题描述】:

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

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

【问题讨论】:

标签: flutter sorting dart flutter-layout flutter-web


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是一个使用内置函数.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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 2015-01-02
      • 2010-10-17
      • 2011-12-28
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      相关资源
      最近更新 更多