错误:使用weather API时,flutter中出现XMLHttpRequest错误



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

错误:XMLHttpRequest错误。C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 908:28获取当前软件包/http://src/browser_client.dart 69:22C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1687:54 runUnaryC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_inpl.dart 160:18 handleValueC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_inpl.dart 767:44 handleValueCallbackC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_inpl.dart 796:13 _propagateToListenersC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_inpl.dart 593:7[_complete]C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.art 61:11 _cancelAndValueC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.art 1232:7C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart334:14 _checkAndCallC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart339:39 dcallC:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37332:58在Object.createErrorWithStack(http://localhost:51980/dart_sdk.js:5388:12)在对象处_重新思考(http://localhost:51980/dart_sdk.js:40987:16)异步_异步回调条目.new.callback(http://localhost:51980/dart_sdk.js:40981:13)在对象处_microtaskLoop(http://localhost:51980/dart_sdk.js:40808:13)在_startMicrotaskLoop(http://localhost:51980/dart_sdk.js:40814:13)在http://localhost:51980/dart_sdk.js:36279:9

我的颤振代码是:

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

}

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

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

相关内容

  • 没有找到相关文章