[英]How to get the List of Document Reference from a Snapshot Document resulting from a Firestore query
I can't seem to figure out how to get a List after querying a specific Firestore collection.在查询特定的 Firestore 集合后,我似乎无法弄清楚如何获取列表。
I want the function to:我希望 function 能够:
This is what I am trying:这就是我正在尝试的:
import 'package:cloud_firestore/cloud_firestore.dart';
Future<List<ChatsRecord>> getChatDoc(
DocumentReference chatUserRef,
DocumentReference authUserRef,
) async {
// Add your function code here!
final firestore =
FirebaseFirestore.instance; // Get a reference to the Firestore database
final collectionRef =
firestore.collection('chats'); // Get a reference to the collection
final filteredDocuments = collectionRef.where('users', isEqualTo: [
authUserRef,
chatUserRef
]); // Use the `where` method to filter the list of documents
final queryDocuments = await filteredDocuments
.get(); // You can then use the get method on this Query object to retrieve the list of documents AS a Snapshot Document (this is NOT a list of the Documents themselves).
List<ChatsRecord> listChatDocs = [];
// Cast the Snapshot Documents to a map
// Extract the Document Reference ID
// cast the query document to a map for e
// (should I forEach?)
List<ChatsRecord> listChatDocs = queryDocuments.docs.map((e) {
return FirebaseFirestore.instance.doc('chats/$e.id');
}).toList();
return listChatDocs;
}
Does your ChatsRecord
object contain fromSnapshot
factory method like this?:您的
ChatsRecord
object 是否包含这样的fromSnapshot
工厂方法?:
factory ChatsRecord.fromSnapshot(DocumentSnapshot snapshot) {
Map<String, dynamic> data = snapshot.data();
return ChatsRecord(
chatId: snapshot.id,
users: data['users'],
lastMessageTime: data['lastMessageTime'],
);
}
If no, create factory
function similar to mentioned above in your ChatsRecord
class and try to do forEach
your queryDocuments
in your last code snippet:如果不是,请在您的
ChatsRecord
class 中创建类似于上面提到的factory
function 并尝试在最后一个代码片段中执行forEach
您的queryDocuments
:
List<ChatsRecord> listChatDocs = [];
queryDocuments.docs.forEach((docSnapshot) {
// Convert each document snapshot into a ChatsRecord object
ChatsRecord chat = ChatsRecord.fromSnapshot(docSnapshot);
// Add the ChatsRecord object to the list
listChatDocs.add(chat);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.