alexlee11111
alexlee11111

Reputation: 109

How to call async function one by one in the initState function with Flutter

Assume that I would like get the data from the backend server, and I called the API by post method at the initState. I would like to call the following function one by one.

Map response = {};
Map response2 = {};

void initState() {
   callAPI_1();
   callAPI_2();
   ShowData();
}

void callAPI_1() async {
   .
   .
   .
   HttpClientResponse responseBody = await request.close();

   this.setState((){
      response = responseBody;
   });
}


void callAPI_2() async {
   .
   .
   .
   HttpClientResponse responseBody2 = await request2.close();

   this.setState((){
      response2 = responseBody2;
   });
}

void ShowData() {
   print(response);
   print(response2);
}

Expecting the order of the programming flow should be initState -> callAPI_1 -> callAPI_1 -> ShowData;

Any suggestion of how to achieve it?

Upvotes: 0

Views: 434

Answers (2)

Sam Chan
Sam Chan

Reputation: 1772

You can use SchedulerBinding.instance.addPostFrameCallback

like

@override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      await callAPI_1();
      await callAPI_2();
      ShowData();
    });
  }

Upvotes: 2

Jahidul Islam
Jahidul Islam

Reputation: 12595

Try this

Map response = {};
Map response2 = {};

void initState() {
   asyncMethod();
   
}
asyncMethod() async{
await callAPI_1();
await callAPI_2();
await  ShowData();


void callAPI_1() async {
   .
   .
   .
   HttpClientResponse responseBody = await request.close();

   this.setState((){
      response = responseBody;
   });
}


void callAPI_2() async {
   .
   .
   .
   HttpClientResponse responseBody2 = await request2.close();

   this.setState((){
      response2 = responseBody2;
   });
}

void ShowData() {
   print(response);
   print(response2);
}

Upvotes: 2

Related Questions