Home > Back-end >  .where() not working with StreamBuilder steam | firestore query require an index - Flutter
.where() not working with StreamBuilder steam | firestore query require an index - Flutter

Time:12-17

I want to display groups with this condition

  • current user id must include in the members array of group collection
  • order by LastUpdate (time)

So, I used steam like this

StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("groups")
            .orderBy('LastUpdate', descending: true)
            .where(
              "members",
              isEqualTo: FirebaseAuth.instance.currentUser!.uid,
            )
            .snapshots(),
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.hasError) {
            return Text(
              '${snapshot.error}',
              style: const TextStyle(color: Colors.white),
            );
          }
          if (snapshot.hasData) {
            return Padding(
              padding: const EdgeInsets.only(top: 5),
              child: ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context, index) {
                  return Text(
                    snapshot.data.docs[index]['groupName'],
                    style: const TextStyle(fontSize: 40, color: Colors.white),
                  );
                },
              ),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(color: Colors.white),
            );
          }
        });

When I run first time, It showed error and said,

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

I created it. there is picture of it, enter image description here

With this, Application run without error. But,

  • When I use .where( "members",isEqualTo: FirebaseAuth.instance.currentUser!.uid,), It not display anything. empty without any error. (There are 3 groups, this user id has in the member's array - its sure. I checked it correctly)
  • When I remove .where( "members",isEqualTo: FirebaseAuth.instance.currentUser!.uid,) from snapshot. It working properly.

What can I do to fix this. HELP

CodePudding user response:

If members is an array in a document, you must use "arrayContains" not "isEqualTo"

.where(
   "members",
   arrayContains: FirebaseAuth.instance.currentUser!.uid,
)
  • Related