Pratham Sarankar
Pratham Sarankar

Reputation: 599

Error getting data from subcollection of flutter firebase

In a flutter messaging app, chatrooms are created and on the conversation screen, I can access the subcollection of the messages. But when the same subcollection I am trying to access on the main page (where existing chats are shown) I cannot access them.

I have a collection of ChatRooms, in which users as an array are stored. Then, Messages named subcollection stores the messages.

See, the document is named lexicographically attached with and in between. Further, it has Messages collection.

enter image description here

And messages collection is also not empty.

On the main page, the existing chats are shown in listTile. I want to show the last message in its subtitle.

So, here is the last message stateful widget.

class _LastMessageState extends State<LastMessage> {
  
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore.instance
            .collection("ChatRooms")
            .doc(widget.chatRoomID)
            .collection("Messages")
            .orderBy("Time")
        .snapshots()
        .last,
    builder: (context, documentSnapshot) {
      return Text(documentSnapshot.data.docs.last.get("Message"));
    });
  }
}

Always the bad state error is coming up. I would be glad if you could figure out the problem.

Edit :

This is my firestore rules.

Upvotes: 0

Views: 213

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

You should use the limit() method, in order to get a QuerySnapshot with only one document. Then you can do as follows, knowing the first (and unique) element of the docs list is the document you are looking for:

return FutureBuilder<QuerySnapshot>(
  future: FirebaseFirestore.instance.
        .collection("ChatRooms")
        .doc(widget.chatRoomID)
        .collection("Messages")
        .orderBy("Time", descending: true)
        .limit(1)
        .get(),

  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

    if (snapshot.hasError) {
      return Text("...");
    }

    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.data.size > 0) {
        return Text(snapshot.data.docs[0].get("Message"));
      } else {
        return Text("No document");
      }
    }

    return Text("Loading");
  },
);

Upvotes: 2

Related Questions