如何在dart/flutter中按日期对列表进行排序?

vngu2lb8  于 2022-12-19  发布在  Flutter
关注(0)|答案(7)|浏览(218)

我有以下列表,我尝试按日期时间重新排序。

import 'package:intl/intl.dart'; 
//don't forget to add under dependencies pubspec.yml "intl: ^0.15.8"

List products = [];

//adding into the new list from raw API list
for(final item in rawProducts){

   var parsedDate = DateTime.parse.(item['expiryDate']);
   tmpArray = {
     'id': item['id'],
     'name': item['name'],
     'price': item['price'],
     'expiry': parsedDate
   }
   products.add(tmpArray);
  }
}

List products = [

 {id: 1242, name: milk, price: $5, expiry: 2019-11-25 00:00:00:000},
 {id: 1242, name: egg, price: $2, expiry: 2019-11-22 00:00:00:000},
 {id: 1243, name: bread, price: $3, expiry: 2019-11-22 00:00:00:000},
 {id: 1244, name: butter, price: $7, expiry: 2019-11-24 00:00:00:000},
 {id: 1247, name: butter, price: $7, expiry: 2019-11-23 00:00:00:000},

]

我想以最远失效日期显示在最前面的方式重新排序列表:

25-11-2019
 24-11-2019
 23-11-2019
 22-11-2019
 22-11-2019

我尝试过的(更新)-〉通过将a.expiry更改为a['expiry']解决:

products.sort((a,b) {
    var adate = a['expiry'] //before -> var adate = a.expiry;
     var bdate = b['expiry'] //var bdate = b.expiry;
     return -adate.compareTo(bdate);
  });

在排序功能上,我收到此错误(通过上述修复解决):

Unhandled Exception: NoSuchMethodError: Class 
'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'expiry'.
eulz3vhy

eulz3vhy1#

在上面的示例中,expiryString,而不是DateTime对象。这里有几个选项,具体取决于您想要实现的目标。
最简单的解决方案是使用String内置的compareTo方法,它允许对String进行排序,这些时间戳已经是可排序的格式,所以这样做是可行的:

products.sort((a,b) {
    return a.compareTo(b);
 });

或者更简洁一点:

products.sort((a,b) => a.compareTo(b));

这是非常基本的,就像评论中提到的pskink一样,在此基础上你可以把字符串转换成实际的DateTime对象。

DateTime expiryAsDateTime = DateTime.parse(expiry);

DateTime也有一个内置的compareTo方法,因此上面的代码片段可以与DateTimes以及String一起使用。
如果您想颠倒顺序,只需交换ab

pxq42qpu

pxq42qpu2#

我通过更改changing a.expiry into a['expiry']b.expiry into b['expiry']修复了此问题

products.sort((a,b) {
 var adate = a['expiry'] //before -> var adate = a.expiry;
 var bdate = b['expiry'] //before -> var bdate = b.expiry;
 return adate.compareTo(bdate); //to get the order other way just switch `adate & bdate`
});
tktrz96b

tktrz96b3#

转换为日期时间

import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];
  List<DateTime> newProducts = [];
  DateFormat format = DateFormat("yyyy-MM-dd");

  for (int i = 0; i < 5; i++) {
    newProducts.add(format.parse(products[i]));
  }
  newProducts.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(newProducts[i]);
  }
}

不转换为日期时间

import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];

  products.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(products[i]);
  }
}
eblbsuwk

eblbsuwk4#

如果您遇到类似以下情况:

{
"id": 100,
"timestamp": "2021-02-02T15:15:11Z",
"name": "Entry1"
}

然后执行以下操作:

List<Values> _myList = [];
_myList.sort((a,b)=> a["timestamp"].compareTo(b["timestamp"]));

或者像我的代码:

task.sort((a,b) => a.createdAt.compareTo(b.createdAt));

Source

kx7yvsdv

kx7yvsdv5#

如果我们更具体的话,试试这个。
对我来说效果很好

transactionList.sort((a, b) {
  int aDate = DateTime.parse(a.dateTime ?? '').microsecondsSinceEpoch;
  int bDate = DateTime.parse(b.dateTime ?? '').microsecondsSinceEpoch;
  return aDate.compareTo(bDate);
});
b5lpy0ml

b5lpy0ml6#

假设日期和时间为字符串,如果要按特性名称对对象进行排序而不必使用DateTime,请执行以下操作:

products.sort((a, b)=> a['expiry'].compareTo(b['expiry']));

相关问题