在Dart/Flutter中对Map排序

fkaflof6  于 2023-07-31  发布在  Flutter
关注(0)|答案(2)|浏览(144)

我有一个Map<String,dynamic>,我从一个json响应中得到,如下所示。

map = {
  "status": "Success",
  "payments": [
    {
      "id": 99,
      "groupID": 19,
      "paymentDueDate": "2023-05-12",
      "paymentDate": null,
      "userID": 13,
      "amount": 500,
      "forDuration": "May",
      "proofOfPayment": null,
      "paymentMode": null,
      "paymentID": null,
      "paymentToken": null,
      "approvedBy": null,
      "approvedAt": null,
      "status": "pending",
      "note": "",
      "created_at": "2023-05-09T03:39:01.000000Z",
      "updated_at": "2023-05-09T03:39:01.000000Z"
    }
  ]
};

字符串
我想按“paymentDueDate”排序。这看起来像一个列表的Map。有人可以帮助我如何实现这个排序在扑?下面是我尝试过的,但没有效果。

map["payments"].sort(
    (a, b) => (
      a[DateTime.tryParse('paymentDueDate')].compareTo(
        b[DateTime.tryParse('paymentDueDate')],
      ),
    ),
  );

yzckvree

yzckvree1#

可能是这样的

List<dynamic> payments = map["payments"];
payments.sort((a, b) {
  final DateTime aDate = DateTime.parse(a["paymentDueDate"]);
  final DateTime bDate = DateTime.parse(b["paymentDueDate"]);
  return aDate.compareTo(bDate);
});

字符串

alen0pnh

alen0pnh2#

试试这样做:

map["payments"].sort((a, b) {   
final DateTime? aDueDate = DateTime.tryParse(a?["paymentDueDate"]);
final DateTime? bDueDate = DateTime.tryParse(b?["paymentDueDate"]);

  if (aDueDate == null || bDueDate == null) {
    // Handle null or invalid dates if necessary
    return 0;   }

  return aDueDate.compareTo(bDueDate); });

字符串

相关问题