【问题标题】:How to call async function one by one in the initState function with Flutter如何用 Flutter 在 initState 函数中一一调用异步函数
【发布时间】:2021-07-07 06:31:27
【问题描述】:

假设我想从后端服务器获取数据,并在 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;

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

【问题讨论】:

  • 创建另一个异步函数并从 initState 中调用它,类似这样

标签: flutter dart


【解决方案1】:

您可以使用SchedulerBinding.instance.addPostFrameCallback

喜欢

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2023-03-06
      • 2020-03-09
      • 2022-01-11
      • 2020-07-15
      相关资源
      最近更新 更多