Flutter Firebase rtdb,获取子值返回为空



我正试图从firebase RTDB中检索子级的值,并将其放入列表中,但值返回为空,在打印列表时,它也是空的。代码过去工作时没有任何问题,我所做的唯一更改是将Flutter和依赖项更新到最新版本。

代码:

lastPosition() async {
print(searchID);
// This method grabs the stream of location that is being sent to the database
print("nnnFetching Coordinatesnn");
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,并在对其的任何调用中使用awaitthen

因此,将呼叫移动到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); // 👈