【问题标题】:Why is print(snapshot.hasData) returning true?为什么 print(snapshot.hasData) 返回 true?
【发布时间】:2019-06-23 09:20:31
【问题描述】:

我一定是把hasData 方法误认为QuerySnaphot。在我的StreamBuilder 中,我想返回一个widget,通知用户collection 中没有任何项目被查询。我已经删除了 Firestore 中的集合,所以那里肯定没有数据。但是当我运行以下代码时:

StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance
    .collection('Events')
    .where("bandId", isEqualTo: identifier)
    .snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData) {
        print('code here is being executed 1');// This gets executed
        return Text('helllllp');
      } else {
        print('Code here is being executed2'); //And this gets executed 
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new Text('Loading...');
          default:
            return new ListView(
              children:
                snapshot.data.documents.map((DocumentSnapshot document) {
                  return CustomCard(
                    event: document['event'],
                    location: document['location'],
                    service: document['service'],
                    date: document['date'].toDate(),
                  );
                }).toList(),
              );
            }
          }
        },
      ),

我要做的就是返回一个小部件,通知用户快照是否为空。例如Text('You have no messages')

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    这里的问题是snapshots() 在查询没有返回文档时也会返回QuerySnapshot。因此,您可以像这样扩展您的条件:

    if (!snapshot.hasData || snapshot.data.documents.isEmpty) {
      return Text('You have no messages.');
    } else {
      ...
    }
    

    虽然,实际上你不应该在snapshot.datanull 时返回You have no messages,因为在查询完成之前它是null。因此,我会选择这样的东西:

    if (!snapshot.hasData) {
      return Text('Loading...');
    } 
    if (snapshot.data.documents.isEmpty) {
      return Text('You have no messages.');  
    }
    return ListView(..);
    

    这会忽略错误处理,但也可以添加。
    注意snapshot.hasData 是使用snapshot.connectionState 确定连接状态的替代方法。

    【讨论】:

    • 谢谢!我搜索了几个小时以找到问题。 hasData 真的很混乱,应该重命名
    猜你喜欢
    • 2021-06-11
    • 2021-09-02
    • 2021-09-10
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多