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?

1
  • Create another async function and call it from initState, something like that Commented Apr 12, 2021 at 7:09

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use SchedulerBinding.instance.addPostFrameCallback

like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.