“检查flutter上是否有可用的Internet连接,“

fhity93d  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(174)

我有一个网络调用要执行。但在此之前,我需要检查设备是否有互联网连接。

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

connectivity_plus插件在其文档中声明,它只在存在网络连接时提供信息,而在网络连接到Internet时不提供信息。

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('example.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}
vlf7wbxs

vlf7wbxs1#

要检查互联网是否正常工作,那么你应该向'www.google.com'发出HTTP请求,并检查响应代码。如果响应code == 200,这意味着一切正常,你有工作的互联网连接。
如果你不想这样做,那么你可以使用internet_connection_checker插件。

相关问题