我按照本教程创建聊天。以下是将消息插入Firestore的代码
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
},
);
});
}
正如可以看到groupChatId
要使用上DocumentId
和CollectionId
是2点的ID(发送器和接收器)的组合物。
消除每条消息的代码可以正常工作
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();
在该图片中,您可以看到1条消息和1条消息的聊天,我试图显示当前用户的每次聊天,为此,我将过滤chat
集合中的所有文档,因此用户可以单击它并在聊天时获取列表消息详细信息页面。
我不知道该怎么做,如果您有更好的聊天方法,我将不胜感激
您可以调用getDocuments
和then
方法,在其中可以进行验证,在这种情况下,如果documentID
包含ID ,则可以进行验证。像这样
Firestore.instance.collection("chats").getDocuments().then((value) {
print(value);
value.documents.forEach((element) {
if (element.documentID.contains(currentUserId)) {
DocumentSnapshot document = element;
print(document);
}
});
});
应该可以
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句