【发布时间】:2020-07-13 03:11:58
【问题描述】:
我按照this 教程创建聊天。将消息插入 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
},
);
});
}
如您所见,DocumentId 和 CollectionId 上使用的 groupChatId 是 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 集合中的所有文档,以便用户可以单击它并在 chatd 详细信息页面上获取列表消息。
我不知道该怎么做,如果您有更好的聊天方法,我将不胜感激
【问题讨论】:
标签: flutter dart google-cloud-firestore