I can't seem to figure out how to get a List after querying a specific Firestore collection.
I want the function to:
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?:
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:
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.