首页 > 解决方案 > 如何用 Flutter 在 initState 函数中一一调用异步函数

问题描述

假设我想从后端服务器获取数据,并在 initState 中通过 post 方法调用 API。我想一一调用下面的函数。

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);
}

期望编程流程的顺序应该是initState -> callAPI_1 -> callAPI_1 -> ShowData;

关于如何实现它的任何建议?

标签: flutterdart

解决方案


试试这个

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);
}

推荐阅读