Home > database >  query a specific document inside 2 streamBuilder
query a specific document inside 2 streamBuilder

Time:10-20

I created 2 differents collection( users and follow).

now i want to: 1-fetch document which exist inside the follow's collection("list") according by thier id. 2-fetch users data in the first collection where currentUid = doc.id (for the second collection) 3-display data in the ListTile

First collection

await FirebaseFirestore.instance.collection("users").doc(currentUid).set({"name":username,"photoUrl":url,"uid":currentUid}); 

Second collection

await FirebaseFirestore.instance.collection("follow").doc(currentUid).collection("list").doc(otherId); 

I used this but it doesn't work properly

     body:StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
              .collection("follow")
              .doc(user!.uid)
              .collection("list")
              .snapshots(),
          builder: (context, snapshot1) {
            if (!snapshot1.hasData) {
              return Container();
            } else {
              return StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection("users")
                    .where("uid",
                        isEqualTo:
                            snapshot1.data!.docs.map((e) => e.id).toList())
                    .snapshots(),
                builder: (context, snapshot2) {
                  if (!snapshot2.hasData) {
                    return Container();
                  } else {
                    return ListView(
                      children: snapshot2.data!.docs.map((e) {
                        return ListTile(
                          leading: CircleAvatar(
                            backgroundImage: NetworkImage(e.get('url')),
                            radius: 30,
                          ),
                          title: Text(e.get('username')),
                        );
                      }).toList(),
                    );
                  }
                },
              );

CodePudding user response:

You should use the in query instead of the equal to query.

An in query returns documents where the given field matches any of the comparison values.

The syntax for the in query in the cloud_firestore is this:

 .where(field, whereIn: listOfFields)

Solution:

Change this:

 .where("uid", isEqualTo: snapshot1.data!.docs.map((e) => e.id).toList())

to this:

 .where("uid", whereIn: snapshot1.data!.docs.map((e) => e.id).toList())
  • Related