Ballazx
Ballazx

Reputation: 579

Snapshot has data even if it not exist in Firestore

I have this StreamBuilder:

 SizedBox(
                  height: 200,
                  child: StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance
                        .collection('users')
                        .doc(uid)
                        .collection('favoritePets')
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        print(snapshot);
                        return ListView.builder(
                            itemCount: snapshot.data!.docs.length,
                            itemBuilder: (context, index) {
                              DocumentSnapshot doc = snapshot.data!.docs[index];
                              return Text(
                                doc['title'],
                              );
                            });
                      } else {
                        return Text(
                          "No data",
                        );
                      }
                    },
                  ),
                ),

If the collection does not exist in the Firestore because no items were added or all of the items are removed I got a blank page, instead of showing the "No data" text.

This gets printed no matter whether the collection exists or not:

AsyncSnapshot<QuerySnapshot<Object?>>(ConnectionState.active, Instance of '_JsonQuerySnapshot', null, null)

How is it possible to get the "No data" text?

Upvotes: 0

Views: 483

Answers (1)

Marcelo Abu
Marcelo Abu

Reputation: 97

You have to distinguish snapshot from non existance of the doc. If the doc doesn't exist the snapshot still has data! Non existance is also a data. To acomplish what you want you have to check !snapshot.exists and snapshot.hasData condition. Also you should check the hasError flag.

Hope I helped.

Upvotes: 1

Related Questions