![](/img/trans.png)
[英]Flutter - Firebase RTDB, The method forEach was called on null
[英]Flutter-Firebase rtdb, fetching child values return as empty
我試圖從 firebase RTDB 中檢索一個孩子的值並將它們放入列表中,但值返回空,在打印列表時,它也是空的。 代碼過去沒有任何問題,我所做的唯一更改是將 Flutter 和依賴項更新到最新版本。
代碼:
lastPosition() async {
print(searchID);
// This method grabs the stream of location that is being sent to the database
print("\n\n\nFetching Coordinates\n\n");
databaseReference
.child("users")
.child("Driver Coordinates")
.child(searchID)
.once()
.then(
(DataSnapshot lastPosSnapshot) {
setState(
() {
lastLatLng.add(
lastPosSnapshot.value["latitude"],
);
lastLatLng.add(
lastPosSnapshot.value["longitude"],
);
Future.delayed(
Duration(milliseconds: 100),
);
},
);
},
);
print(lastLatLng);
await getAdressBasedLocation();
}
數據從 Firebase 異步加載,同時你的主代碼繼續執行。 實際上,這意味着您的print(lastLatLng);
在執行后的任何lastLatLng.add(...)
調用之前運行,您也可以通過在then()
處理程序中添加一些日志記錄來最輕松地檢查。
實際上,這意味着任何需要數據庫數據的代碼都必須在then
回調中,或者您必須使用await
來阻止once
調用(在這種情況下,您還必須將lastPosition
標記為async
並使用await
或then
對它的任何調用。
因此,將調用移至then
回調內部:
databaseReference
.child("users")
.child("Driver Coordinates")
.child(searchID)
.once()
.then((DataSnapshot lastPosSnapshot) {
lastLatLng.add(lastPosSnapshot.value["latitude"]);
lastLatLng.add(lastPosSnapshot.value["longitude"]);
print(lastLatLng); // 👈
...
},
);
或者使用await
:
var lastPosSnapshot = await databaseReference
.child("users")
.child("Driver Coordinates")
.child(searchID)
.once();
lastLatLng.add(lastPosSnapshot.value["latitude"]);
lastLatLng.add(lastPosSnapshot.value["longitude"]);
print(lastLatLng); // 👈
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.