Reputation: 4509
I follow this tutorial to create a chat. The code to insert message into Firestore is the follow
var _firebaseRef = Firestore.instance.collection("chats");
void sendMessage(String message, String idFrom, ProductModel productModel,
String fromName) {
String groupChatId;
String idTo = productModel.userId;
if (idFrom.hashCode <= productModel.userId.hashCode) {
groupChatId = '$idFrom-$idTo';
} else {
groupChatId = '$idTo-$idFrom';
}
var documentReference = _firebaseRef
.document(groupChatId)
.collection(groupChatId)
.document(DateTime.now().millisecondsSinceEpoch.toString());
Firestore.instance.runTransaction((transaction) async {
await transaction.set(
documentReference,
{
'message': message,
'idFrom': idFrom,
"productId": productModel.id,
"createdAt": utils.currentTime(),
'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
"fromName": fromName,
"idTo": productModel.userId
},
);
});
}
As you can see the groupChatId
to be used on DocumentId
and CollectionId
is a composition of 2 ids (sender and receiver).
The code to displey each message works fine
String groupChatId;
if (idFrom.hashCode <= idTo.hashCode) {
groupChatId = '$idFrom-$idTo';
} else {
groupChatId = '$idTo-$idFrom';
}
return _firebaseRef
.document(groupChatId)
.collection(groupChatId)
.orderBy('timestamp', descending: true)
.snapshots();
In that picture you can see 1 chat with 1 message, I am trying to display each chat of my current user, to do that I 'd to filter all document inside of chat
collection, so the user can click it and get list message on chatd detail page.
I don't know how to do that, if you have a better approach to do the chat I will appreciate it
Upvotes: 1
Views: 268
Reputation: 8246
you can work with something like this querying for where currentUser Id s equal to IdFrom or IdTo
StreamBuilder(
stream: Firestore.instance
.collection("users")
.orderBy('createAt', descending: true)
.where('idFrom', isEqualTo: currentuserId)
.where('idTo', isEqualTo: currentuserId)
.snapshots(),....
if you run this for the first time check your console for a link to create index
Upvotes: 0
Reputation: 120
You can call getDocuments
and then
methods, inside of it you can make your validations, on this case you can if the documentID
contains your ID. Like this
Firestore.instance.collection("chats").getDocuments().then((value) {
print(value);
value.documents.forEach((element) {
if (element.documentID.contains(currentUserId)) {
DocumentSnapshot document = element;
print(document);
}
});
});
It should works
Upvotes: 1