HTTP 请求中互联网不可用时也没有异常

问题描述 投票:0回答:1

在 Flutter 中执行

HTTP request
时,我没有得到任何
Exception
,例如 WiFi 打开时的
SocketException
,但实际上没有互联网,而是等待很长时间,直到我获得定义的
TimeoutException
。当一开始有网络连接但突然连接断开时也会出现此问题。

如何做到网络出现问题时直接抛出异常?

这是我当前的代码:

try {
  await http
      .get(url, headers: headers)
      .timeout(const Duration(seconds: 20));
} on SocketException catch (e, st) {
  debugPrint('SocketException. Seems to be no internet available');
  debugPrint(e.toString());
  debugPrint('OS Errorcode: ${e.osError?.errorCode.toString()}');
} catch (e, st) {
  debugPrint('Unknown error happen in `tryAndHandle`:');
}
android ios flutter xcode dart
1个回答
0
投票

实际上,如果不 ping 不同的 url 以确保有互联网,就没有办法做到这一点。

或者使用 flutter_offline 来检测变化并做出相应的响应。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.