1

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

1 Answers1

0

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.

Sweet Chilly Philly
  • 3,014
  • 2
  • 27
  • 37
  • I am calling this function in the initState as I mentioned which I shouldn't be awaiting it and not a good practice either. – Muhammad Haroon Jul 05 '20 at 22:46
  • I beleive thats where your problem is, Please try use a lifecycle hook https://stackoverflow.com/questions/44422783/get-the-value-of-a-computed-property-in-vue-js-and-use-it-in-a-data-property this might help – Sweet Chilly Philly Jul 05 '20 at 22:49
  • Also I need this list to be displayed in the build method. According to many people here on SOF, asyncing or awaiting a build method is not a good practice. The only place that I can call this is the initState where it shouldn't be awaited. If I am wrong in any of these statements, please correct me. Thanks – Muhammad Haroon Jul 05 '20 at 22:52
  • I dont think you have to have it in initstate, why cant you just fetch your data when they visit your page, and have it run in a BeforeMounted() function, so it will start processing before the paage loads, and then you will display a loading icon while it waits.Preferrably the store would dispatch this event. These are my thoughts – Sweet Chilly Philly Jul 05 '20 at 22:54
  • the code here is a dart code flutter framework. I think the BeforeMounted() you talked about is from Javascript.. Is there something like that in Dart/Flutter? – Muhammad Haroon Jul 05 '20 at 23:00
  • Sure mate have a read of this: https://stackoverflow.com/questions/41479255/life-cycle-in-flutter I have no expertise in what you're doing, but I am just trying to help since no one else replied – Sweet Chilly Philly Jul 05 '20 at 23:26