bricend96
bricend96

Reputation: 61

Query a specific document inside 2 streamBuilder

I created 2 different collections (users and follow).

Now I want to:

  1. Fetch document which exist inside the follow's collection("list") according by their 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(),
                    );
                  }
                },
              );

Upvotes: 0

Views: 40

Answers (1)

Victor Eronmosele
Victor Eronmosele

Reputation: 7716

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())

Upvotes: 1

Related Questions