提问者:小点点

错误:XMLHttpRequest错误在颤振而使用天气API


在这里,我使用天气API。在调试时,它会出现错误,

我的flutter代码是:

    String searchApiUrl = 'https://www.metaweather.com/api/location/search/?query=';
    String locationApiUrl = 'https://www.metaweather.com/api/location/';


    void fetchSearch(String input) async {
     var searchResult = await http.get(Uri.parse(searchApiUrl + input), headers: {"Accept": 
      "application/json","Access-Control-Allow-Origin": "*"});
  
     var result = json.decode(searchResult.body)[0];

   setState(() {
    location = result["title"];
    woeid = result["woeid"];
});

}

    void fetchLocation() async {
     var locationResult = await http.get(Uri.parse(locationApiUrl + woeid.toString()), 
      headers: {"Accept": "application/json","Access-Control-Allow-Origin": "*"});
     var result = json.decode(locationResult.body);
     var consolidated_weather = result["consolidated_weather"];
     var data = consolidated_weather[0];

   setState(() {
    temperature = data["the_temp"].round();
    weather = data["weather_state_name"].replaceAll(' ','').toLowerCase();
});

}

   void onTextFieldSubmitted(String input){
    fetchSearch(input);
    fetchLocation();

}


共1个答案

匿名用户

fetchPlace中,您依赖于来自fetchSearchwoeid值,但您不必等待onTextFieldSub的中的结果。试试这个:

void onTextFieldSubmitted(String input) async {
    await fetchSearch(input);
    await fetchLocation(); // await in this line might not be needed
}