0

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}
Amol Borkar
  • 2,321
  • 7
  • 32
  • 63
  • You will have to get them each individually. It's not as bad as it seems. – Doug Stevenson Jul 11 '19 at 13:41
  • 1
    Since you get a Future using `.get()` method you can try and add `await` before that line and `async` in the signature of your function. This way you will wait for that statement to terminate before returning the result. – Ryk Jul 11 '19 at 13:43
  • @Ryk I'm doing as you said but still the function returns an empty `List`. See updated code. – Amol Borkar Jul 11 '19 at 14:09
  • @AmolBorkar I'd also add a catchOn error method to see if the function fails to run. Does your print method, print something to the console? – Ryk Jul 11 '19 at 15:01
  • @Ryk Yes, It prints the empty result list, then the correct data is printed after the future resolves. – Amol Borkar Jul 11 '19 at 15:42
  • @Ryk Actually no, the 'Interests' Print statement executes just before the function returns result list which is empty. The fetched print statement with the correct data runs in the then block before it is added to the result list. So as you can see the function is infact returning an empty list which is not what I want. – Amol Borkar Jul 11 '19 at 18:07
  • I've also added a 'Function Call' print statement which calls the function and prints the data from `.then` part which as you can see is also an empty list @Ryk – Amol Borkar Jul 11 '19 at 18:09

0 Answers0