variable not being changed out of then scope in flutter

222

then is an async call which not called sequentially, that why the second print statement is not giving length

use:

@override
  void initState() {
    super.initState();
    asyncInitState(); // async is not allowed on initState() directly
  }

  void asyncInitState() async {
     var value = await etabController.AfficherEtablissement();
    value.forEach((entry) {
      int id = entry["id"];
      Etablissement et = new Etablissement(id);
      this.etablist.add(et) ;
      print("etablist length inside the loop "+etablist.length().toString());
    }) 
      print("etablist length outside the loop "+etablist.length().toString());
  }
Share:
222
silver123
Author by

silver123

Updated on December 23, 2022

Comments

  • silver123
    silver123 over 1 year

    i have a Future< dynamic > List and List of objects , i am accessing the Future < dynamic > List using '.then' and in the same scope i am adding objects into the List of objects . This is the code :

       List<Etablissement> etablist = new List<Etablissement>() ;
       //AfficherEtablissement() returns Future<dynamic>
        etabController.AfficherEtablissement().then((value) =>
        value.forEach((entry) {
          int id = entry["id"];
          Etablissement et = new Etablissement(id);
          this.etablist.add(et) ;
          print("etablist length inside the loop "+etablist.length().toString());
        })
        ) ;
          print("etablist length outside the loop "+etablist.length().toString());
    

    the etablist length inside the loop is prinitng '2' so there are objects being added to the list but outside the loop scope it's empty like nothing has been added .

  • silver123
    silver123 over 3 years
    so that means the list is not empty even outside the scope ?
  • Jigar Patel
    Jigar Patel over 3 years
    yes, but after a while. Specifically, after the time it takes to resolve the Future. After that, the list will not be empty even outside the scope. Because outside or inside, it is the same list. It is just empty at the beginning. And not empty after the future is resolved.
  • Jigar Patel
    Jigar Patel over 3 years
    You can also observe the sequence of execution from the console. You might have noticed in the console, that the print text which is outside the scope occurs before the print text which is inside the scope.
  • silver123
    silver123 over 3 years
    yes the list is not empty outside of the scope , but i am getting this error because i added async modifier to the state 'Future<void> initState() async' so i got this error : 'Rather than awaiting on asynchronous work directly inside of initState, call a separate method to do this work without awaiting it. '
  • Jitesh Mohite
    Jitesh Mohite over 3 years
    @silver123: modified the answer, have a look. It should work for you now