skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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();

    @override
    void initState () {
      super.initState();
      WidgetsBinding.instance.addPostFrameCallback((_){
        _asyncMethod();
      });    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search