gpt4 book ai didi

flutter - 如何使用Flutter过滤Firestore文档?

转载 作者:行者123 更新时间:2023-12-03 03:32:54 28 4
gpt4 key购买 nike

我遵循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
},
);
});
}
如您所见,在 groupChatId上使用的 DocumentIdCollectionId由2个ID(发送者和接收者)组成。
这是它的样子:
enter image description here
消除每条消息的代码可以正常工作
 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集合内的所有文档,因此用户可以单击它并获得列表消息。聊天的详细信息页面。
我不知道该怎么做,如果您有更好的聊天方法,我将不胜感激

最佳答案

您可以调用getDocumentsthen方法,在其中可以进行验证,在这种情况下,如果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);
}
});
});
应该可以

关于flutter - 如何使用Flutter过滤Firestore文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868718/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com