[英]Flutter: Reading and merging firestore data by date
我正在尋找一種方法來按日期合並我從 Cloud Firestore 讀取的數據。 我的目標是從 Cloud Firestore 讀取所有文檔,然后將特定日期的所有文檔放在 ONE ExpansionTile
下。 即每個日期一個ExpansionTile
,每個ExpansionTile
可能包含許多單獨的文檔,具體取決於當天上傳的文檔數量。
我在從 Cloud Firestore 讀取數據時沒有問題,但是一旦掌握了手頭的信息,我就很難弄清楚如何按日期組織和合並文檔。 請記住,會有多個不同的日期,每個日期都有不同數量的文件。
如下圖所示,我目前有三個具有相同日期的文檔,因此在應用程序中創建它們時有三個不同的ExpansionTiles
。 我希望將這三個轉換為一個ExpansionTile
我目前正在使用flutter_bloc package 按日期從 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());
}
}
對於那些可能好奇的人,這是我對問題的解決方案。 它可能有點冗長,所以任何縮短/改進它的建議仍然非常感謝:
//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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.