【发布时间】:2019-12-30 05:10:41
【问题描述】:
我是 Flutter & Dart 的新手,正在尝试完成我的第一个应用程序。
我无法捕获(使用 try-catch 块)http.get SocketException(当您调用 API 并关闭 WiFi 时会发生这种情况)
我在互联网上尝试了一切都没有运气,我什至尝试(Dio)包来捕获这个异常,但没有成功。
如何重现:使用底部代码...关闭手机的 WiFi...调用 API...现在应用程序在您的 IDE 中因 (SocketException) 而崩溃。
这是我的简单代码(更新)
RaisedButton(
child: Text("Call API"),
onPressed: () async {
try {
http.Response response = await getLoginResponse();
//do something with response
print(response.body);
} catch (e) {
print("Button onPressed Error: " + e.toString());
}
},
)
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
return http.get(loginUrl).timeout(Duration(seconds: 10))
.then((response) {
return response;
}, onError: (e) {
print("onError: " + e.toString());
}).catchError((err) {
print("catchError: " + err.toString());
return null;
});
}
【问题讨论】: