Flutter - Is there a way to load async metho on InitState?

Viewed 602

Flutter - Is there a way to load async metho on InitState? i want to call async method in iniState(); but it is not worked...

I'm a looking for a way to load async data on InitState method, I need some data before build method runs. I need to execute build method 'till a Stream runs.

    @override
      void initState () {
        super.initState();

         //here i want to call async function
      }
2 Answers

You can create a separate method and can call in the initState(). Moreover you can use WidgetBinding to call the function like this.

void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_)  => {
      your_method();
    // TODO: implement initState
    super.initState();
  }

You could try with a below code snippet.

Method 1 : Create an async method and call it from you initState() method like shown below:

 @override
   void initState() {
   super.initState();
   asyncMethod();
   }

   void asyncMethod() async {
   await asyncCall1();
   await asyncCall2();
   // ....
  }
Related