如何在飞镖/颤振中按日期对列表进行排序/排序? [英] How to sort/order a list by date in dart/flutter?

查看:81
本文介绍了如何在飞镖/颤振中按日期对列表进行排序/排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表,我想按DateTime重新排序/排序。

I have the following list, that I am trying to re-order/ sort by the DateTime.

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},

]

我想以最远的到期日期重新排序列表首先显示:

I would like to re-order the list in a way that the farthest expiry date shows up first:

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

我做什么尝试(更新)->通过将 a.expiry 更改为 a ['expiry'] 来解决:

What I have tried (updated) -> SOLVED by changing a.expiry into 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);
  });

关于排序功能,我收到此错误(由以上修复解决):

on the sort function I am receiving this error (SOLVED by above fix):

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


推荐答案

在上面的示例中,到期时间 String ,而不是DateTime对象。

In your example above, expiry is a String, not a DateTime object. You have a few options here, depending on what you want to achieve.

最简单的解决方案是使用String内置的 compareTo 方法,该方法可以进行排序字符串。这些时间戳已经是可排序的格式,因此可以使用:

The easiest solution would be to use String's built in compareTo method, which allows sorting Strings. Those timestamps are already in a sortable format, so this would work:

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

或更简洁:

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

这是非常基本的。就像注释中提到的pskink一样,可以在此基础上将字符串转换为实际的DateTime对象。

This is pretty basic. Like pskink mentioned in the comment, building on this you could convert the Strings to actual DateTime objects.

DateTime expiryAsDateTime = DateTime.parse(expiry);

DateTime 也具有内置的 compareTo 方法,因此上面的代码段将与DateTimes以及Strings一起使用。

DateTime also has a built in compareTo method, so the code snippet above would work with DateTimes as well as Strings.

如果要反转顺序,只需交换 a b

If you want to reverse the order, just swap a and b.

这篇关于如何在飞镖/颤振中按日期对列表进行排序/排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆