我有一个网络调用要执行。但在此之前,我需要检查设备是否有互联网连接。
这是我目前为止所做的:
var connectivityResult = new Connectivity().checkConnectivity();// User defined class
if (connectivityResult == ConnectivityResult.mobile ||
connectivityResult == ConnectivityResult.wifi) {*/
this.getData();
} else {
neverSatisfied();
}
上述方法行不通。
迟答,但用这个包来检查。
包名:data_connection_checker
在你的酒吧里。yuml文件:
dependencies:
data_connection_checker: ^0.3.4
创建一个名为connection的文件。达特,随便你叫什么都行。
导入包:
import 'package:data_connection_checker/data_connection_checker.dart';
检查是否有网络连接:
print(await DataConnectionChecker().hasConnection);
连接插件在其文档中声明,它只在有网络连接的情况下提供信息,但不包括网络连接到Internet的情况
请注意,在Android上,这并不保证连接到互联网。例如,应用程序可能有wifi接入,但它可能是一个VPN或酒店wifi,没有接入。
你可以使用
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');
}
更新
不建议使用连接包。请使用官方的Flutter Community connectivity_plus包。