[英]string name dose not change dart flutter
im assigning the string name in this code to a name from a document but it dose not change from null i cant see why.我将此代码中的字符串名称分配给文档中的名称,但它不会从 null 改变我不明白为什么。
i will use this variable inside a listTile我将在 listTile 中使用这个变量
String name='';
FirebaseFirestore.instance
.collection('Users')
.doc('list_students')
.collection('Students')
..where('Email', isEqualTo: userEmail)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
name = doc['Full Name'];
});
});
As commenters have said, most of your code is running asynchronously, because the data needs to be loaded from the cloud.正如评论者所说,您的大部分代码都是异步运行的,因为需要从云端加载数据。 This messes up the order in which your code runs, and is likely why the variable doesn't have a value.这会打乱代码运行的顺序,这可能是变量没有值的原因。
Some logging should make this clearer:一些日志记录应该使这一点更清楚:
String name='';
print("1. Before starting query");
FirebaseFirestore.instance
.collection('Users')
.doc('list_students')
.collection('Students')
..where('Email', isEqualTo: userEmail)
.get()
.then((QuerySnapshot querySnapshot) {
print("2. Got data");
querySnapshot.docs.forEach((doc) {
name = doc['Full Name'];
});
});
print("3. After starting query");
When you run this code, the output will be:当您运行此代码时,output 将是:
Before starting query开始查询前
After starting query开始查询后
Got data得到数据
This is probably not the order you expected, but is actually working as intended.这可能不是您预期的顺序,但实际上按预期工作。 And this means that if you'd print the name
in the place of 3.
you'd not see the value from the database.这意味着如果您将name
打印在3.
的位置,您将看不到数据库中的值。
The solution for this is always the same: the code that needs the data from the database needs to be inside the then
callback, or it needs to be called from there, or it needs to be otherwise synchronized to run when the data has loaded.解决方案总是相同的:需要来自数据库的数据的代码需要在then
回调中,或者需要从那里调用,或者需要在加载数据时同步运行。
For example, if you want to use the name
in the UI of your app, you can store it in the state of your (stateful) widget by wrapping it like this:例如,如果您想在应用程序的 UI 中使用该name
,您可以将其存储在(有状态)小部件的 state 中,如下所示:
setState(() {
name = doc['Full Name'];
})
Now Flutter knows that it needs to update the UI after the data has loaded.现在 Flutter 知道它需要在数据加载后更新 UI。
Since this is such a common occurrence, there is a dedicated widget to handling it known as a FutureBuilder
.由于这种情况很常见,因此有一个专用的小部件来处理它,称为FutureBuilder
。 So I recommend reading up on that too.所以我建议也阅读一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.