[英]FirebaseFirestore.get returning null - Fluter
I'm trying to fetch data from Firestore.我正在尝试从 Firestore 获取数据。
class _TestState extends State<Test> {
bool abcd;
final adsRef = FirebaseFirestore.instance.collection('All ads');
getData(){
adsRef.get().then((snap) {
snap.docs.forEach((doc) {
abcd=doc.data().isEmpty;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text("TestPage"),
),
body: FlatButton(
onPressed: () {
print(abcd);
},
child: Text("data"),
),
);
}
}
And I've tried getting doc.id
, doc.exists
, etc我试过获取
doc.id
、 doc.exists
等
but It's returning 'null'.但它返回“空”。
PS: I'm a newbie to firebase. PS:我是firebase的新手。
Data is loaded from Firebase/Firestore (and most modern cloud APIs) asynchronously, and needs to be passed to the UI through a setState()
call (or another state management primitive).数据从 Firebase/Firestore(和大多数现代云 API)异步加载,需要通过
setState()
调用(或其他状态管理原语)传递到 UI。
You should:你应该:
initState
method of the classinitState
方法中开始加载数据setState()
when the data is available (or changes)setState()
)build()
method, where you can then use the data from the statebuild()
方法,然后您可以在其中使用状态中的数据So something like:所以像:
class _TestState extends State<Test> {
bool abcd;
final adsRef = FirebaseFirestore.instance.collection('All ads');
@override
void initState() {
super.initState();
adsRef.get().then((snap) {
snap.docs.forEach((doc) {
setState(() {
abcd=doc.data().isEmpty;
});
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text("TestPage"),
),
body: FlatButton(
onPressed: () {
print(abcd);
},
child: Text("data"),
),
);
}
}
You need to use "Async/Await" to get data from firebase您需要使用“Async/Await”从 firebase 获取数据
async getData()异步获取数据()
and call并打电话
data = await getData() like this. data = await getData() 像这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.