Home > Software design >  firestore doesnt show documents even though they are available
firestore doesnt show documents even though they are available

Time:11-29

I have following code to add data to firebasefirestore

Future<void> sendMessage({
    required String msg,
    required String id,
  }) async {
    var docId = getDocId(id);    // returns sth like "AbcDe-FghiJ"
    DocumentReference documentReferencer = chat.doc(docId).collection('chatMsg').doc();

    Map<String, dynamic> data = <String, dynamic>{
      "message": msg,
      "sentBy": ownId,
      "sentAt": DateFormat('yyyy-MM-dd – kk:mm:ss').format(DateTime.now())
    };

    await documentReferencer.set(data);
  }

Console stores data as image below

I used following code to get the data

StreamBuilder<QuerySnapshot>(
  stream: firebaseInstance.collection('Messages').snapshots(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.hasError || !snapshot.hasData) {
      return const Center(
        child: CircularProgressIndicator()
      );
    } else {
      var data = snapshot.data.docs;
      return listBuilder(data);
    }
  }
)
listBuilder(listData) {
  return ListView.builder(
    shrinkWrap: true,
    itemCount: listData.length,
    itemBuilder: (BuildContext context, int index) {
      return Text(listData[index].id);
    }
  )
}

However, data show 0 items even though there is a document present.

My question is how can I get the list of documents from Messages?

CodePudding user response:

I was having the same exact problem with subcollections on Firestore and even asked a question here to get some help over it. Though, it seems like the snapshots won't show the documents having a subcollection in them as there is no field inside any of them. So what I did to counter this was to just add anything (just a random variable) and then it was able to find the documents.

This is my current layout: Firestore Console

I've just added another line of code to just add this whenever I'm inserting a new subcollection.

               collection
                    .set({
                      'dummy': 'data'
                    })
                    .then((_) => print('Added'))
                    .catchError((error) => print('Add failed: $error'));
  • Related