For an instance, let's suppose I am calling a function in initState which gets some documents from the Firebase collection. I am iterating on those documents using async forEach and need to perform an await operation to get some data from another collection from firebase and saving them in a list then returning after the forEach is finished. But the returned list is empty as the second await function completes after return statement. How do I handle this? I have a hard time understanding Asynchronous programming so please a detailed explanation will be highly appreciated.

The code here is just an example code showing an actual scenario.

Future getList() async {

    //These are just example refs and in the actual refs it does print actual values
    var collectionOneRef = Firestore.instance.collection('Collection1');
    var collectionTwoRef = Firestore.instance.collection('Collection2');
    List<Map<String, dynamic>> properties = [];

    QuerySnapshot querySnapshot = await collectionOneRef
        .getDocuments()
        .then((query) {
      query.documents.forEach((colOneDoc) async {
        var colOneID = colOneDoc.documentID;
        await collectionTwoRef.document(colOneID).get().then((colTwoDoc) {
          Map<String, dynamic> someMap = {
            "field1": colTwoDoc['field1'],
            "field2": colTwoDoc['field2']
          };

          properties.add(someMap);

          properties.sort((p1, p2) {

            //sorting based on two properties
            var r = p1["field1"].compareTo(p2["field1"]);
            if (r != 0) return r;
            return p1["field2"].compareTo(p2["field2"]);
          });

          print(properties); //this prints actual data in it

         ));
        });
      });
    });

    print(properties); //This prints a blank list as [] and obviously returns blank list 

    return properties; 
  }

And now when I call this function in an initState of a stateful Widget and display it somewhere, it display a blank list. BUT, after I "Hot Reload", then it displays. I want to get the data and display it without hot reloading it. Thanks in advance


Solution 1: Sweet Chilly Philly

Sounds like you need to await the whole function itself in the block of code where you are calling getList().

you are async'ing and awaiting inside the function, and that looks fine which is why you are getting results when hot reloading. But it might be the case that you're not actually awaiting the entire function itself in the code that is calling this. Please Check.