0

Can someone help why this code return no message when it obvious that their a data in my message collection when i tried to get the last message to display in the widget below.

![message collection][1]

![1]: https://i.stack.imgur.com/uGJgV.png

  final ChatMethods chatMethods = ChatMethods();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          widthFactor: 5,
          child: Text(
            'Message',
            style: mystyle(
              20.0,
              Style.Colors.titleColor,
            ),
          ),
        ),
      ),
      body: StreamBuilder(
        stream: chatMethods.fetchLastMessageBetween(
            senderId: firebaseAuth.currentUser.uid, receiverId: widget.uid),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasData) {
            
            var docList = snapshot.data.docs;

            if (docList.isNotEmpty) {
              Message message = Message.fromMap(docList.last.data());
              return SizedBox(
                width: MediaQuery.of(context).size.width * 0.6,
                child: Text(
                  message.message,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 14,
                  ),
                ),
              );
            }
            return Text(
              "No Message",
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            );
          }
          return Text(
            "..",
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          );
        },
      ),
    );
  }
}
  • 1
    Does this answer your question? [Get last created document in a Firebase Firestore collection](https://stackoverflow.com/questions/54178951/get-last-created-document-in-a-firebase-firestore-collection) – Abbas Jafari Mar 02 '21 at 12:23
  • i do not understand the code, because i am using stream builder to get the data. – matthew abbey Mar 02 '21 at 14:53

1 Answers1

1

Yes there is. descending ordering and limit to 1 will get you the result.

this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
this.history = this.historyRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as Hisotory;
        const docId = a.payload.doc.id;
        return { docId, ...data };
    });
});

original answer from: Get last created document in a Firebase Firestore collection

Marcel Dz
  • 2,321
  • 4
  • 14
  • 49