Home > Mobile >  how to where query a collectionGroup in firestore flutter?
how to where query a collectionGroup in firestore flutter?

Time:10-06

I need to query a collectionGroup with where clause and While doing it I stumbled on to a thing.

var payData = FirebaseFirestore.instance.collectionGroup("payment").where("balance", isNotEqualTo: 0);

While executing the above code when I tried to print payData it prints Instance of _JsonQuery. How to access the data inside that variable and what's its structure.

I think the above code is incorrect.

var payData = FirebaseFirestore.instance.collectionGroup("payment").where("balance", isNotEqualTo: 0).getDocuments();

After surfing I got through the above code but VSCode says it's an error in getDocuments()

So, What I need is to print the data that is in the variable for the query I used above.

CodePudding user response:

getDocuments() was deprecated in favor of get() in version 0.14.0 of the cloud_firestore package (Release notes). You need to call this method on your Query, i.e. payData.

The get() method returns a Future, so you can use then() as follows:

FirebaseFirestore.instance
    .collectionGroup("payment")
    .where("balance", isNotEqualTo: 0)
    .get()
    .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
            print(doc["<name_of_a_field_in_the_doc>"]);
        });
    });

However, most of the times you will use one of the approaches shown in the FluterFire doc: depending on whether you want to read the data once or listening to changes in realtime you will use a FutureBuilder or a StreamBuilder.

  • Related