关闭。这个问题需要debugging details .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
1年前关闭。
Improve this question
我正在构建一种从 Firebase(Cloud Firestore)读取信息的方法,但是在调用时这些值没有分配给变量,有人可以帮忙吗?
有 testt 变量只是为了测试 Method 是否被调用并正在运行,但我不明白为什么其他变量没有得到任何值。
class _VehicleDetailsState extends State<VehicleDetails> {
String speed, place, testt;
void displayData() {
testt = "Test";
FirebaseFirestore.instance
.collection('Cars')
.where('id', isEqualTo: Routes.idCar)
.get()
.then((value) {
value.docs.forEach((result) {
place = result.data()['place'];
speed = result.data()['speed'];
});
});
}
@override
Widget build(BuildContext context) {
displayData();
print(testt);
print(place);
return Scaffold(
appBar: new AppBar(
title: new Text(
'Vehicle Details',
style:
new TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () {
Navigator.of(context).popAndPushNamed(Routes.routeName);
},
),
),
);
}
}
最佳答案
Firestore 是异步的,这意味着您可以向它询问信息,它会在后台获取该信息,同时您的代码继续工作。这就是你的值(value)观没有改变的原因;因为在其余代码执行时 Firestore 还没有它们。
你可以通过两种方式来解决这个问题。使用 await
关键字,或 .then()
方法。你猜怎么着,你已经使用了.then()
您的firestore调用中的方法!你告诉它去获取数据,然后执行你放在 .then()
中的任何代码。打回来。
`
//Ran right away
FirebaseFirestore.instance.collection('Cars').where('id', isEqualTo :Routes.idCar).get().then((value){
//Ran only once data has been retrieved from firestore (which usually takes a few milliseconds)
value.docs.forEach((result) {
place = result.data()['place'];
speed = result.data()['speed'];
});});`
获取数据的另一种方法是使用 await
关键词。 await 关键字表示“等待这个异步函数给我一个值,然后继续执行其余代码”。但是,为了使用 await 关键字,它所在的函数也需要是异步的。如果您考虑一下,这是有道理的,因为您不希望整个代码锁定在一个 Web 请求上。如果失败了怎么办?然后你的整个应用程序被卡住!这是一个使用与以前相同类型的代码的示例。Future<void> displayData() async {
testt = "test";
// Waits for firestore to give back the value, then executes the rest of the code.
dynamic value = await FirebaseFirestore.instance.collection('Cars').where('id', isEqualTo :Routes.idCar).get();
// The below code only starts once the above code has a value.
value.docs.forEach((result) {
place = result.data()['place'];
speed = result.data()['speed'];
});
您可能会注意到 Future<void>
哪里只是 void
以前是。这是一个 Future,它是 Flutter 中大多数异步事物的基础。您可以使用 await 然后就可以了。对于您的代码,我很抱歉,但您可能需要进行一些重组以考虑加载数据。您的构建方法不能是异步的,但您可以从
displayData()
对 UI 进行适当的更改。方法。TL;博士:
它是空的,因为它还没有值。
关于firebase - Flutter Firebase 数据库变量在方法后未收到值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64574264/