【问题标题】:how to handle StreamBuilder listening to non-existent snapshot?如何处理 StreamBuilder 监听不存在的快照?
【发布时间】:2021-06-16 02:25:05
【问题描述】:

我想要实现的只是只要文档存在于云 Firestore 中……我的流构建器会一直监听它的快照……如果出于某种原因……该文档已从云 Firestore 集合中删除,我想要安全无误地发送至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'),

       ]));



      }
    );

从这一点开始,一切都按预期运行,但是当我打开 Cloud Firestore 集合并从集合中手动删除文档时...应用程序崩溃并且我收到此错误:

The method '[]' was called on null.
Receiver: null
Tried calling: []("postTitle")

回顾一下:

我想手动从 Cloud Firestore 集合中删除该文档...应用程序安全地确定该文档不再存在...所以它@98​​7654324@ 当前屏幕

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    尝试在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 所需的 hack。或者,您可以使用SchedulerBinding.addPostFrameCallback,这将产生相同的结果。

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 2021-10-21
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      相关资源
      最近更新 更多