我正在為一個聊天應用系統的應用構建一個部件,但我有點迷路了。
發布到 Firebase 的請求代碼
FirebaseFirestore.instance
.collection('messages')
.doc(user.uid)
.collection(widget.receiver)
.add({
'message': _textEditingController.text,
'messageType': "sender",
'receiver': widget.receiver,
'sender': user.uid,
'timestamp': DateTime.now()
.millisecondsSinceEpoch
.toString(),
});
獲取訊息
FirebaseFirestore.instance
.collection('messages')
.doc(user.uid)
.collection(widget.receiver)
.where('receiver', isEqualTo: widget.receiver)
.snapshots(),
訊息發送,但如果我想檢索它以進行一對一使用,它不會顯示。難道我做錯了什么?
uj5u.com熱心網友回復:
你做錯了什么是.doc(user.id). 您正在為每個用戶創建單獨的檔案,其中包含單獨的集合。因此,要從用戶那里獲取訊息,您需要傾聽每個用戶可能想要向您發送訊息。我不知道小部件接收器是什么,它是用戶 ID 嗎?
好吧,在整個應用程式中發送訊息的最簡單方法是:
發送:
FirebaseFirestore.instance
.collection('messages')
.add({
'sender': user.uid,
'receiver': reciever.uid, // user ID you want to read message
'message': _textEditingController.text,
'messageType': "sender", // i dont know why you need this ?
'created': FieldValue.serverTimestamp(), // I dont know why you called it just timestamp i changed it on created and passed an function with serverTimestamp()
});
獲取訊息:
FirebaseFirestore.instance
.collection('messages')
.where('created' ???) // This need to be first if you want to use orderby() method. Question marks for you to solve what need to be there.
.where('receiver', isEqualTo: user.uid) // This line is important to get any data out of message collection if you won't have it, rules will kick your request.
.where('sender', isEqualTo: friend.uid) // If you want to get documents only from specific friend.
.orderBy('created', 'desc') // ordered from newest to latest message.
.limit(20) // take just 20 documents. Max limit for one request 100 doc.
.snapshots(),
您將需要再次請求發送給用戶的訊息并在應用程式中合并對話。
每個人都寫在一個集合中,所以每個人只需要聽一個集合。如果您使用 Firestore 規則限制對集合內檔案的正確訪問,則這種方式是可以的。
規則:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /messages/{messageId} {
allow create: if request.auth.uid != null
allow update: if request.auth.uid == resource.data.sender
allow read: if request.auth.uid == resource.data.sender || request.auth.uid == resource.data.recaiver
}
}
}
如果您想擁有多個接收器,只需從接收器欄位中創建一個陣列并更改有關讀取操作的規則。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/484327.html
上一篇:如何過濾資料框的列?
