Why is my snapshot showing it contains data?

I have a stream builder:

 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());
            }
          },
        ),

When the collection('sources')doesn't exist I'm expecting hello to be displayed but instead the

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

code gets executed. The collection doesn't exist on firestore...so I'm wondering why this is happening?

1 answer

  • answered 2019-05-21 13:11 SwiftingDuster

    You are probably getting an empty list [] but it isn't null so hasData is set to true.

    You should check the length of the result:

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