为什么我的快照显示它包含数据?

时间:2019-05-21 11:14:27

标签: firebase dart flutter google-cloud-firestore

我有一个流生成器:

 StreamBuilder(
          stream: Firestore.instance
              .collection('stripe_customers')
              .document(userId)
              .collection('sources')
              .document('source')
              .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return new Text("hello");
            }else {
              var userDocument = snapshot.data;
              return new Text(userDocument["card"]['exp_year'].toString());
            }
          },
        ),

collection('sources')不存在时,我希望显示hello,但会显示

{
              var userDocument = snapshot.data;
              return new Text(userDocument["card"]['exp_year'].toString());
            }

代码被执行。该集合在Firestore上不存在...所以我想知道为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

您可能会得到一个空列表[],但不是null,因此hasData设置为true。

您应该检查结果的长度:

if (!snapshot.hasData || snapshot.data.length == 0) {
   // Nothing found here...
}