首页 > 解决方案 > 在颤动中如何设置等待未来的方法

问题描述

我有三个 api,第一个 api 负责获取一些数据,用于第二个 api,依此类推,第二个 api 负责第三个 api 所需的一些数据。我做了3个未来的功能。它们是按顺序排列的。例如 ,

  int datafromapi_one;
  bool datafromapi_two;
  bool datafromapi_three;

  Future getDataFromApi_one() async {

    http.Response api_one_response = await http.get("http://api_one_url");
    int data_from_api_one = json.decode(api_one_response.body); // the response data is in numeric only

    setState(){

      datafromapi_one = data_from_api_one;

    }

  }

  Future getDataFromApi_two() async {

    http.Response api_two_response = await http.get("http://api_two_url?with_parameter=datafromapi_one");
    bool data_from_api_two = json.decode(api_two_response.body); // the response data is in boolean value

    setState(){

      datafromapi_two = data_from_api_two;

    }

  }



  Future getDataFromApi_three() async {

    http.Response api_three_response = await http.get("http://api_three_url?with_parameter=datafromapi_two");
    bool data_from_api_three = json.decode(api_three_response.body); // the response data is in boolean value

    setState(){

      datafromapi_three = data_from_api_three;

    }

  }



  FlatButton(
  onPressed:(){

  getDataFromApi_one();
  print(datafromapi_one.toString());

  getDataFromApi_two();
  print(datafromapi_two.toString());

  getDataFromApi_three();
  print(datafromapi_three.toString());

  if(datafromapi_three == true && datafromapi_two == true && datafromapi_one != null ){

  // Navigate.to.next.screen()//

  }
  else{
  // Toast.Show( error on which api )
  }
  }
  )

我实现了这种方法,并且卡在了应用程序中,有时来自 api_one 的数据稍后会收到,并且如果没有来自第一个 api 的数据,依赖的 api 就无法正常工作。现在我想在 api_two 上设置一些等待功能,这样如果数据没有到达,那么它必须等待数据直到它到达,然后使用该数据运行第二个 api,并希望让 api_three 等待直到数据到达. 然后运行 ​​api_three。我希望您能理解并为我提供适当的解决方案。

标签: androidjsonapiflutterfuture

解决方案


推荐阅读