【发布时间】:2021-04-27 17:22:00
【问题描述】:
我正在颤振中构建一个列表,需要通过首先显示最近的时间戳来按日期对其进行排序。
该列表是从如下所示的 json 创建的:
[
{
"id":100,
"timestamp":"2021-02-02T15:15:11Z",
"name":"Entry1"
},
{
"id":101,
"timestamp":"2021-03-02T11:12:56Z",
"name":"Entry2"
}
]
使用fetchEntries 函数获取json 后,我想对列表进行排序。这是我的代码:
class Values extends Object {
int id;
String timestamp;
String name;
Values(
{this.id,
this.timestamp,
this.name});
Values.fromJson(Map<String, dynamic> json) {
id = json["id"];
timestamp = json["timestamp"];
name = json["name"];
}
}
List<Values> _myList = [];
fetchReport() {
_timer = new Timer.periodic(Duration(seconds: 1), (timer) {
fetchEntries(dates.id.toString(), dates.from, dates.to)
.then((value) => {
_myList.addAll(value),
_postsController.add(1),
setState(() {})
});
_timer.cancel();
});
//This is the sort code that doesn't work
_myList.sort((a,b)=> a.timestamp.compareTo(b.timestamp));
}
或者,列表可以按 id 降序排序,但首选时间戳方法。任何建议如何正确地做到这一点?
【问题讨论】:
-
您需要在比较它们之前解析时间戳。
-
为什么时间戳是一个字符串?它应该是摄取时的 DateTime,否则 Values 的所有用户都需要独立进行相同的计算!
标签: android flutter sorting dart