我正在寻找一种按日期合并从Cloud Firestore读取的数据的方法。我的目的是从Cloud Firestore中读取所有文档,然后将某个日期的所有文档放在一个ExpansionTile
下。即每个日期一个ExpansionTile
,每个ExpansionTile
可能包含许多单独的文件,具体取决于当天上传了多少文件。
我从Cloud Firestore读取数据没有问题,但是一旦掌握了信息,我就很难弄清楚如何按日期组织和合并文档。请记住,会有多个不同的日期,并且每个日期都有不同数量的文件。
如下图所示,我目前拥有三个具有相同日期的文档,因此在应用程序中创建它们时,三个ExpansionTiles
也不同。我希望将这三个转换成一个ExpansionTile
我目前正在使用flutter_bloc软件包按日期从Cloud Firestore中读取数据:
//Retrieves firebase data of all orders done in the past
Stream<OrderHistoryState> _loadOrderHistory() async* {
try {
_orderSubscription?.cancel();
var orderHistory = Firestore.instance
.collection('orders')
.orderBy('date', descending: true);
_orderSubscription = orderHistory.snapshots().listen(
(event) {
if (event.documents.length > 0) {
add(OrderHistoryUpdate(
documents: event.documents,
));
} else {
print("No Order to Load");
add(NoOrderHistory());
}
},
);
} catch (e) {
print("Error with Tracking Status, $e");
add(ErrorOrderHistory());
}
}
答案 0 :(得分:1)
对于那些可能好奇的人,这是我解决问题的方法。可能会花很多时间,所以任何缩短/改进它的建议仍然值得赞赏:
//Make sure that there are documents within firebase
if (state.orderHistoryDocuments.length != 0) {
//Adding the first document manually so that
//the forloop section has something to compare dates
//This listForEachDate is for storing a collection
//of all documents of one date
listForEachDate = [state.orderHistoryDocuments[0].data];
//listOfDateLists is a list of all listForEachDate
//This gives us a list of lists with the documents
//separated by date i.e.
//[[date1, date1], [date2], [date3, date3, date3], etc]
listOfDateLists = [];
//i = 1 because index 0 already added above
for (int i = 1;
i < state.orderHistoryDocuments.length;
i++) {
//If the current index's date matches that of the previous
//index's date, then add it to the listForEachDate
if (state.orderHistoryDocuments[i]
.data["dateCreated"] ==
state.orderHistoryDocuments[i - 1]
.data["dateCreated"]) {
listForEachDate
.add(state.orderHistoryDocuments[i].data);
//If [index]date does not match [index - 1]date
//Then add the current listForEachDate to the
//listOfDateLists i.e. add sublist to list of lists
} else {
listOfDateLists.add(listForEachDate);
//Clear the listForEachDate so that we can create
//a new clean list of new dates
listForEachDate = [];
//Add the new date to the listForEachDate
//so that the process can start again
listForEachDate
.add(state.orderHistoryDocuments[i].data);
}
}
//Once the document has been iterated through,
//Add to the big list.
listOfDateLists.add(listForEachDate);
}