I want to use FutureBuilder, but make it build after waiting for 2 async functions to end.
In the Flutter docs, it says Widget that builds itself based on the latest snapshot of interaction with a Future.
So it builds after one function, not waiting for the other.
Future<int> futureInit() async {
await functionA();
await functionB();
return 0;
}
My code is like this, so the future builder builds after just function A.
How can I make it wait for the both functions to end and then start building?
CodePudding user response:
first you have to know how to handle future function.
there are 2 approach. with await
and with then
here my article explain more about it : await vs then in Flutter
if you want to handle 2 future function in 1 FutureBuilder
,you can use Future.wait
. here an old question related:https://stackoverflow.com/a/50627153/12838877
Future<A> functionA();
Future<B> functionB();
FutureBuilder(
future: Future.wait([functionA, functionB]),
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
snapshot.data[0]; //functionA
snapshot.data[1]; //functionB
},
);
CodePudding user response:
I think below code will work. you can use .then() function. It will execute one after another. please check this and revert
Future<int> futureInit() async {
await functionA().then((func) async {
await functionB();
});
return 0;
}
CodePudding user response:
You can delay your FutureBuilder
by using:
Future<int> futureInit() async {
await functionA();
await functionB();
// Make your delay here.
await Future.delayed(const Duration(milliseconds: 500));
// And trigger future builder.
return 0;
}