You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何检测设备是否具备可用的互联网连接?

Flutter 检测设备是否具备真实互联网连接

如果你需要在发起网络请求前确认设备能真正访问互联网,仅用connectivity_plus插件是不够的——它只能检测设备是否连接了移动网络或WiFi,但无法判断该网络是否能正常访问互联网(比如连接了无网的WiFi时,插件会返回已连接,但实际无法联网)。

原有代码的局限

你之前的代码仅判断了网络连接状态:

var connectivityResult = new Connectivity().checkConnectivity();// User defined class
if (connectivityResult == ConnectivityResult.mobile ||
    connectivityResult == ConnectivityResult.wifi) {
  this.getData();
} else {
  neverSatisfied();
}

这种方式无法覆盖「有网络连接但无互联网访问」的场景。

正确的互联网连通性检测方法

可以通过dart:io库中的InternetAddress.lookup来检测是否能解析并访问某个可靠域名(比如example.com),从而确认真实的互联网连接:

import 'dart:io';

// 封装成异步检测方法
Future<bool> hasInternetConnection() async {
  try {
    final result = await InternetAddress.lookup('example.com');
    return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
  } on SocketException catch (_) {
    return false;
  }
}

// 实际使用示例
void checkBeforeRequest() async {
  if (await hasInternetConnection()) {
    this.getData();
  } else {
    neverSatisfied();
  }
}

这个方法通过尝试解析域名并获取其原始地址,能有效判断设备是否具备真实的互联网访问能力,弥补了connectivity_plus的局限性。

内容的提问来源于stack exchange,提问作者Kunj Bhuva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:29:57