0

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?

alexlee11111
  • 87
  • 1
  • 10

2 Answers2

2

You can use SchedulerBinding.instance.addPostFrameCallback

like

@override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      await callAPI_1();
      await callAPI_2();
      ShowData();
    });
  }
Sam Chan
  • 1,665
  • 4
  • 14
1

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);
}
Jahidul Islam
  • 11,435
  • 3
  • 17
  • 38