我正在构建一个 List
Future<List<Map<String, dynamic>>>? getData(List<String> subcategory) async {
List<Map<String, dynamic>> allData = [];
try {
String? email = FirebaseAuth.instance.currentUser!.email;
var categories = Utils.categoriesDropdownItems;
for (var i = 0; i < subcategory.length; ++i) {
var doc = await FirebaseFirestore.instance
.collection(email!)
.doc(categories[0])
.collection(subcategory[i])
.get();
allData.addAll(doc.docs.map((doc) => doc.data()).toList());
}
allData.sort(); //Unsure how to approach sorting by timestamp??
我不确定如何提取创建的字段以便对其进行排序。我尝试做类似的事情:
allData.sort((a, b) => a["cretedOn"].compareTo(b["createdOn"]));
但是对于 a["createdOn"] 来说似乎不存在compareTo?
解决了。我只需确保时间戳定义如下:
allData.sort(((a, b) {
Timestamp one = a["createdOn"];
Timestamp two = b["createdOn"];
return two.compareTo(one);
}));
您可以像这样使用 orderBy 在 firestore 查询中直接订购它们
.collection(subcategory[i]).orderBy('createdOn', descending: true);
您可以使用带有自定义比较函数的排序方法。
void main() {
List<Map<String, dynamic>> data = [
{'timestamp': 1639791020, 'value': 'Item 1'},
{'timestamp': 1639794320, 'value': 'Item 2'},
{'timestamp': 1639792120, 'value': 'Item 3'},
// Add more items as needed
];
// Sorting the list based on the 'timestamp' field in descending order
data.sort((a, b) => b['timestamp'].compareTo(a['timestamp']));
// Printing the sorted list
print(data);
}
希望这对您有帮助。