variable not being changed out of then scope in flutter

Viewed 309

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 .

2 Answers

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());
  }

The print statement outside of the then scope is executed before the print statement inside the then block. Which is the reason why the former prints the list as empty.

This is because the then block waits for the Future to resolve and only after that executes the code inside it. Meanwhile the print which is outside of it is already executed.

Related