I have a function that accepts a list of ids and is supposed fetch all the documents with those ids and then return a List<Map<String, dynamic>>
. The first problem I ran into is that Firestore for flutter has no function to get multiple documents from a collection in a single network call. (Am I missing something here?
)
So, I'm running a forEach loop on the list of ids and add the data I get to an empty list like so:
interestIds.forEarch((id) {
_db.collection('interests').document(id).get().then((DocumentSnapshot snap) {
result.add(snap.data);
}
});
return result;
As you might have guessed this doesn't really work because the return
statements get executed before all the documents are fetched. How do I solve this problem??
Updated Code as told in comments:
Future<List<Map<String, dynamic>>> getAllInterestsOfUser(
List<String> interestIds) async {
//Returns list of all intrests objects given a list of interestIds
List<Map<String, dynamic>> result = List();
await interestIds.forEach((id) {
_db
.collection('interests')
.document(id)
.get()
.then((DocumentSnapshot snap) {
print('Fetched: ' + snap.data.toString());
result.add(snap.data);
});
});
print('Interests: ' + result.toString());
return result;
}
Application Output:
I/flutter (12578): Interests: []
I/flutter (12578): Function Call: []
I/flutter (12578): Fetched: {conversationId: -LjS54Q0c7wcQqdwePT6, 49wotilxfSRbADygh7kt3TSscnz1: {//moredata}