Ad
Variable Not Being Changed Out Of Then Scope In Flutter
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
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad