Search code examples
firebasefluttergoogle-cloud-firestorewhere-clausestream-builder

Flutter firebase stream has data but returns null


I have a Problem there are some documents in Firestore that have the same location and the location gets passed correctly as it prints out the right string, but my StreamBuilder always executes the noData function in the if condition.

The Streambuilder looks like this:

StreamBuilder(
                      stream: FilterFirebase().relatedLocationFilter(
                          eventDocument["location"], eventDocument["id"]),
                      builder: (BuildContext ctx,
                          AsyncSnapshot<QuerySnapshot> snapshot) {
                        if (!snapshot.hasData ||
                            snapshot.data.docs.isEmpty) {
                          return NoDataRelatedLocation();
                        } else {
                          return new RelatedLocationListing(
                            relatedLocationList: snapshot.data.docs,
                          );
                        }
                      },
                    )

My relatedLocationFilter looks like this:

relatedLocationFilter(String location, String id) {
print(location);
print(id);
return FirebaseFirestore.instance
    .collection("events")
    .where("location", isEqualTo: location)
    .where("id", isNotEqualTo: id)
    .snapshots();
}

The security rules are normal and the code without the where filters is working fine.

Update:

Logs:

flutter: Tj4EB68R1CwBYKPfWzcm

flutter: MGM Banquet Hall

flutter: 1

Firestore Docs:

First Document

Second Dcoument

Third Document


Solution

  • That is the correct desired result. So though your stream returns the proper value, the stream builder first gets null before your stream gets data. So if you don't want to show NoDataRelatedLocation before your stream gets real data, you should put initialData param of your stream builder.