[英]Query data from FirebaseFirestore not working
I want to query the data in a collection in Firestore.我想查询 Firestore 集合中的数据。 This is the code I used in initState:
这是我在 initState 中使用的代码:
@override
void initState() {
super.initState();
var nws;
FirebaseFirestore.instance
.collection('News')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
nws = doc["news"] // PRINT STATEMENT 1
print(nws);
});
});
print(nws); // PRINT STATEMENT 2
}
The issue I am facing is that PRINT STATEMENT 1
is correctly printing the data in Firestore but PRINT STATEMENT 1
is printing null .我面临的问题是
PRINT STATEMENT 1
正在 Firestore 中正确打印数据,但PRINT STATEMENT 1
正在打印 null 。 What is my mistake?我的错误是什么? I want to use nws in a Text Widget.
我想在文本小部件中使用 nws。
var news;
void getFirebaseData() async {
await FirebaseFirestore.instance.collection("News").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
setState(() {
news = result.data();
});
});
});
print("***2***" + news['news'].toString());
}
Let me know if this works out, It's tested and working.让我知道这是否可行,它已经过测试并且可以正常工作。 You should handle null values I would suggest adding a null value checker like
您应该处理 null 值我建议添加一个 null 值检查器,例如
if (result.data().isEmpty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.