Flutter按时间戳对Firebase快照进行排序 [英] Flutter sort Firebase snapshot by timestamp
本文介绍了Flutter按时间戳对Firebase快照进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按时间戳对快照进行排序,但返回原始顺序.
数据结构看起来像这样
I'm trying to sort snapshot by timestamp but returns original order.
data structure looks like this
我有两个快照,时间戳记分别是-1536025466539
和-1536025893015
.
因此,我希望-1536025893015
在排序后排在第一位.
有人知道如何正确排序吗?
I have two snapshot and timestamps are -1536025466539
and -1536025893015
.
So, I expect -1536025893015
to come first after sorted.
Does anyone know how to sort correctly?
代码:
Map<dynamic, dynamic> map = snapshot.data?.snapshot?.value;
map.values.toList().sort((a, b) {
return a['timestamp'].compareTo(b['timestamp']);
// also not work return b['timestamp'].compareTo(a['timestamp']);
});
推荐答案
从上面的代码看来,您没有variable
来保存列表.
From the above code, it looks like you are not having a variable
to hold the list.
Map<dynamic, dynamic> map = {
"one": {"timestamp": 1},
"two": {"timestamp": 2}
};
List list = map.values.toList(); //variable which holds new list created from Map.
//As it new list, any change in list will not have no impact on map.
list.sort((a, b) {
return b["timestamp"].compareTo(a["timestamp"]);
}); // inplace sort
print(list); // [{timestamp: 2}, {timestamp: 1}]
如果您还要在结果中显示key
,
If you want key
also in the result,
var list = map.entries.toList();
list.sort((a, b) => b.value["timestamp"].compareTo(a.value["timestamp"]));
var list2 = list.map((a) => {a.key: a.value}).toList();
print(list2); // [{two: {timestamp: 2}}, {one: {timestamp: 1}}]
这篇关于Flutter按时间戳对Firebase快照进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文