2021年1月17日星期日

get last message from firestore

I have a firestore collection like the following. I need to get the last stored message.

Firestore-root    |    --- chat_rooms(collection)          |          --- chats(collection, the id for that collection is sender_reciever)               |               --- time_send: (millisecondsSinceEpoch)               |               --- sender:(string)               |               --- message:(string)        

This is my db method to get the last messaeg

  getLastMessage(String chatRoomId) {      return  Firestore.instance.      collection('chat_rooms').document(chatRoomId)          .collection('chat').orderBy('time_send',descending: false)          .limit(1);    }  

Here I am calling it. Chats is a widget that returns the sender and last_message. Basically what I am trying to do is, for instance, while using whatsapp the last message pops on home page.I am trying to do exact same thing. That way, I could get the username too. The method below does not return actual user data. Since the collection chat_rooms_id has an id that is combination username of sender and reciever. I am just removing the reciever which is the current user.And, the sender remains.

   return Chats(                        username: snapshot.data.documents[index]                            .data["chat_room_id"] // return chat_room id                            .toString()                            .replaceAll("_", "")                            .replaceAll(Constants.signedUserName, ""),                        chatRoomId:                            snapshot.data.documents[index].data["chat_room_id"],                        last_message: _db                            .getLastMessage(snapshot                                .data.documents[index].data["chat_room_id"]                                .toString())                            .data[0]['message']                            .toString(),                      );    
https://stackoverflow.com/questions/65766593/get-last-message-from-firestore January 18, 2021 at 06:19AM

没有评论:

发表评论