我正在開展一個專案,讓員工將物品掃描到垃圾箱中。我正在嘗試從資料庫中加載資訊。我查看了許多不同的帖子,發現了類似的東西,但從來沒有任何有效的東西。
我有一個要向其中添加資料的串列(binListDBList),然后我想用它做一些事情。我確實得到了回應,它是正確的資料,但我必須做一個定時延遲而不是等待。它很笨重,我想知道更好的解決方案是什么。
我已經嘗試過 async/await 和 .then,但到目前為止沒有任何效果。我知道有一個解決方案,但我花了很多時間,但沒有得到任何地方。
我添加了一堆列印陳述句進行測驗。
啟動方法:
Future<void> loadBinListFromDB(String empID, String binName) async {
print("start");
DatabaseService.binListDBList.clear();
print("Zero: " DatabaseService.binListDBList.toString());
await DatabaseService().getBinList(empID, binName);
print("test");
if (DatabaseService.binListDBList.isEmpty) {
print("No Data");
} else {
print("data");
}
print("Fifth: " DatabaseService.binListDBList.toString());
Future.delayed(new Duration(seconds: 1)).then((value) {
print("last: " DatabaseService.binListDBList.toString());
});
print(DatabaseService.binListDBList);
return;
}
資料庫服務類
static List<BinListDB> binListDBList = [];
Future<void> getBinList(String employeeID, String binName) async {
print(employeeID);
List<BinListDB> hold = [];
print("First: $binListDBList");
binListCollection
.doc(employeeID)
.collection(binName)
.snapshots()
.forEach((element) {
for (int i = 0; i < element.docs.length; i ) {
hold.add(BinListDB.fromFireStore(element.docs[i]));
}
print("Second: $binListDBList");
binListDBList = hold;
print("Third: $binListDBList");
});
print("Fourth: $binListDBList");
return;
}
輸出:
I/flutter (26448): start
I/flutter (26448): Zero: []
I/flutter (26448): EmployeeID
I/flutter (26448): First: []
I/flutter (26448): Fourth: []
I/flutter (26448): test
I/flutter (26448): No Data
I/flutter (26448): Fifth: []
I/flutter (26448): finish
I/flutter (26448): Second: []
I/flutter (26448): Third: [Instance of 'BinListDB']
I/flutter (26448): last: [Instance of 'BinListDB']
我不明白為什么它沒有按順序列印。
非常感謝任何幫助,并感謝您的閱讀。
uj5u.com熱心網友回復:
您目前正在做:
binListCollection .doc(employeeID) .collection(binName) .snapshots() .forEach((element) { ... });
snapshots()
回傳 a Stream
,它是異步的。您呼叫Stream.forEach
迭代 的每個元素Stream
,并Stream.forEach
回傳 aFuture
以指示它何時完成,但您忽略await
了Future
。因此,呼叫者會立即繼續執行,并且在's 的回呼列印“第二”和“第三”Stream.forEach
之前,您會看到列印的“第四”(以及后來的“第五”和“完成”) 。Stream.forEach
也就是說,您需要將其更改為:
await binListCollection
.doc(employeeID)
.collection(binName)
.snapshots()
.forEach((element) {
...
});
我強烈建議啟用unawaited_futures
lint以讓分析器捕獲此類錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480680.html
上一篇:從回傳Task.FromResult(...)的方法中讀取Task.Result屬性是否安全?
下一篇:返回列表