Ad

Variable Not Being Changed Out Of Then Scope In Flutter

- 1 answer

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 .

Ad

Answer

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());
  }
Ad
source: stackoverflow.com
Ad