I’m trying to understand the flow of build when I execute an async function with setState inside initState. For example:
@override
void initState() {
asyncMethod();
super.initState();
}
asyncMethod() async {
some async call here
setState(){}
}
I first thought that initState procs build, then setState from asyncMethod procs build again or vice versa (which cames first). But on my tests, build is getting called just once. How does this work?
I am just curious about the criteria of calling build on this situation.
2
Answers
The provided callback is immediately called synchronously. It must not return a future (the callback cannot be async), since then it would be unclear when the state was actually being set.
The above line is from Flutter doc of setState callback.
You’ll get an error if you call await in initState to setState. The error will be something as "Set state called during build".
However it’s possible to add a "PostFrameCallback" that will be executed after the first build. You can use await as normally in the _asyncMethod();