0

This is the code where I'm trying to fetch the docs Ids but it returns no documents found.

subcollection chats contain documents based on each product id and that document contains a collection of known Messages that has documents of each message. Below are the images of Firestore. There is a user collection that contains user ids based on each user id(current) I'm trying to access the subcollection and that subcollection contains documents based on each product id on which chat is done and then there are documents that contain messages.

Image1: Image1 of cloud firestore

Image2: Image2 of cloud firestore

Here is the code:

return Scaffold(
  appBar: AppBar(
    title: const Text('Subcollection Documents'),
  ),
  body: FutureBuilder<QuerySnapshot>(
    future: FirebaseFirestore.instance
        .collection('Users')
        .doc(user!.uid)
        .collection('Chats')
        .get(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      } else if (snapshot.hasError) {
        return Center(
          child: Text('Error: ${snapshot.error}'),
        );
      } else if (snapshot.hasData) {
        final documents = snapshot.data!.docs;
        return ListView.builder(
          shrinkWrap: true,
          primary: true,
          itemCount: documents.length,
          itemBuilder: (context, index) {
            final docId = documents[index].id;
            return ListTile(
              title: Text(docId),
            );
          },
        );
      } else {
        return const Center(
          child: Text('No documents found.'),
        );
      }
    },
  ),
);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Faizan
  • 1

1 Answers1

0

If you look carefully in both screenshots, you can see that the document ID in the Chats is printed in italics. This means that there is not actually a document at that path in the database, and the console only shows that ID because there is a collection underneath it (in your case the Messages collection).

Since there is no actual document in the Chats collection, this code will get no results:

FirebaseFirestore.instance
    .collection('Users')
    .doc(user!.uid)
    .collection('Chats')
    .get(),

To address the problem, make sure that you create an actual document inside the Chats collection. You don't necessarily need to put any data in it, but the document must exist in order to be able to read it with your query.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807