我想要实现的只是只要文档存在于cloudfirestore中。。。。我的streambuilder一直在听它的快照。。。如果出于某种原因。。该文档已从cloudfirestore集合中删除,我希望Navigator.of(context).pop()
安全无任何错误。
这是我现在的StreamBuilder:
return StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('posts')
.document(widget.passedPostId)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
),
);
}
String postTitle = snapshot.data['postTitle'];
String postBody = snapshot.data['postBody'];
return Container(child: Column(children:[
Text('$postTitle'),
Text('$postBody'),
]));
}
);
从这一点来看,一切都按预期进行,但当我打开cloudfirestore集合并手动从集合中删除文档时。。。应用程序崩溃,我得到这个错误:
The method '[]' was called on null.
Receiver: null
Tried calling: []("postTitle")
回顾一下:
我想手动从cloud firestore集合中删除该文档。。。并且应用程序安全地确定该文档不再存在。。。因此它Navigator.of(context).pop()
当前屏幕
尝试在DocumentSnapshot
上使用exists
属性。
https://pub.dev/documentation/firebase/latest/firebase_firestore/DocumentSnapshot/exists.html
if (!snapshot.hasData) {
return LoadingWidget();
}
if (!snapshot.data.exists) {
Future.delayed(Duration.zero).then((_) {
Navigator.of(context).pop();
});
return SizedBox();
}
return DataWidget();
Future
是在构建完成后执行pop
所需的破解。或者,您可以使用SchedulerBinding.addPostFrameCallback
,它将产生相同的结果。