-1

I wrote this piece of code and it is causing some problems:

static getFriendsRequests({required id}) async {

QuerySnapshot snapshot = await friendsRef
    .doc(id)
    .collection('received')
    .get();

List<friendRequestItem> feedItems = [];
snapshot.docs.forEach((doc) async{
  DocumentSnapshot extracted = await usersRef.doc(doc.reference.id).get();
  MyUser tempUser = MyUser.fromJsonDocument(extracted);
  String url = '';
  tempUser.profilePictureURL=='' ? null : url=tempUser.profilePictureURL;
  FriendRequest fr = FriendRequest(
      userID: tempUser.userID, uniqueName: tempUser.uniqueName,
      name: tempUser.name, mediaURL: url);
  print(fr.uniqueName+fr.name+fr.userID+fr.mediaURL);
  feedItems.add(friendRequestItem(friendReq: fr));
});
return feedItems;}

To help reading the code, the first query is to get a list of documents, each referring to a unique id. In the second, for each document I search again in the database for some data of the given id. Now I noticed that the problem should be related to the async methods because all the data I get are correct but probably the return happens before the end of the second method. How can I solve? Tell me if you need more infos about other parts of the code. Thank you

Lorenzo Cutrupi
  • 626
  • 3
  • 13

1 Answers1

2

I had the same problem (How to await a Map.forEach() in dart).

To solve this issue, you need to use a for (var mapEntry in map) {}. The map would be the map would be the map you are looping through. This also works for Lists or any Iterable<T>. See the question I linked for more detail.

Please let me know if you need anymore help or anything with my answer is not working.