Get users messages
harunB10 opened this issue · 16 comments
Is it possible from this data model to get a list of my previous chats with last message shown. Like the one in Messenger or WhatsApp after you login...
Right now you save the document in collection like idFrom - idTo ... But I am struggling to query it for a user with uid.
Sure!
At the main.dart add this widget inside buildItem.
Widget getLastMessage(String userId, String peerId) {
String groupChatId = '';
if (userId.hashCode <= peerId.hashCode) {
groupChatId = '$userId-$peerId';
} else {
groupChatId = '$peerId-$userId';
}
return StreamBuilder(
stream: _firestore
.collection('messages')
.document(groupChatId)
.collection(groupChatId)
.orderBy('timestamp', descending: true)
.limit(1)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text('Loading...');
} else {
var documentsData = snapshot.data.documents;
if (documentsData[0]['type'] == 1) {
return Text('Image message');
} else {
return Text(documentsData[0]['content']);
}
}
}
);
}
But if I don't know apeerId?
I contacted person A, B and C. I need an overview of last chats, something like this
So basically you are mapping over the list of users you have chatted. So you have avatar url, user name & id. In this case while mapping items call the Widget getLastMessage with the peerId of current item id.
Hopefully I was clear! :)
If I understood correctly, then in this case I have to save that list of users I've chatted with (in DB, or cache)?
Yes!
If you are coming from this project example as I said you should call the Widget getLastMessage at the main.dart inside buildItem
Whenever a chat is initiated, please check if its the first chat between the current user and the peer, if its the case, save a new instance of that chat with time reference in a firestore table called chats, also save the last message there. when the app loads, take a chat list from that table.in this case, the last message will be stored there. if this is not the first chat, just update the time and the last message sent. this was my approach
@akiligedeon I referred your idea and did a similar thing, but one thing I am not getting is that when the user list will be retrieved with the last message, if the last message is a image, how should it be dealt with?
Hi,
Good one. I am using this project example. If current user or peer user get new message, it is coming as push notification in notification tray. Along with push notification, i want to show new message count in chat list screen as badge like whatsapp also.
Attached sample image. How can i acheive this. Please help me on this.
Ok. Thanks for your reply. Any other suggestion without using rx dart package ? As i am not aware of Rxdart.
watch these two videos ,one deal with combine latest the othere deals with stream
Thank you. i will watch.
