我有一个网络调用要执行。但在此之前,我需要检查设备是否有互联网连接。
这是我目前为止所做的:
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);
我最终(虽然不情愿)选择了@abernee在之前回答这个问题时给出的解决方案。我总是尝试在我的项目中尽可能少地使用外部包——因为我知道外部包是我所创建的软件的唯一[潜在]故障点。所以链接到两个外部包只是为了一个简单的实现,像这样对我来说并不容易。
尽管如此,我还是采用了abernee的代码,并对其进行了修改,使其更精简、更合理。我说的明智是指他在自己的功能中消耗了Connectivity包的功能,但在内部由于没有从这个包中返回最有价值的输出(即网络标识)而浪费了它。这是阿伯尼解决方案的修改版本:
import 'package:connectivity/connectivity.dart';
import 'package:data_connection_checker/data_connection_checker.dart';
// 'McGyver' - the ultimate cool guy (the best helper class any app can ask for).
class McGyver {
static Future<Map<String, dynamic>> checkInternetAccess() async {
//* ////////////////////////////////////////////////////////////////////////////////////////// *//
//* INFO: ONLY TWO return TYPES for Map 'dynamic' value => <bool> and <ConnectivityResult> *//
//* ////////////////////////////////////////////////////////////////////////////////////////// *//
Map<String, dynamic> mapCon;
final String isConn = 'isConnected', netType = 'networkType';
ConnectivityResult conRes = await (Connectivity().checkConnectivity());
switch (conRes) {
case ConnectivityResult.wifi: //* WiFi Network: true !!
if (await DataConnectionChecker().hasConnection) { //* Internet Access: true !!
mapCon = Map.unmodifiable({isConn: true, netType: ConnectivityResult.wifi});
} else {
mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.wifi});
}
break;
case ConnectivityResult.mobile: //* Mobile Network: true !!
if (await DataConnectionChecker().hasConnection) { //* Internet Access: true !!
mapCon = Map.unmodifiable({isConn: true, netType: ConnectivityResult.mobile});
} else {
mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.mobile});
}
break;
case ConnectivityResult.none: //* No Network: true !!
mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.none});
break;
}
return mapCon;
}
}
然后你可以在代码中的任何地方通过简单的调用来使用这个静态函数,如下所示:
bool isConn; ConnectivityResult netType;
McGyver.checkInternetAccess().then(
(mapCIA) { //* 'mapCIA' == amalgamation for 'map' from 'CheckInternetAccess' function result.
debugPrint("'mapCIA' Keys: ${mapCIA.keys}");
isConn = mapCIA['isConnected'];
netType = mapCIA['networkType'];
}
);
debugPrint("Internet Access: $isConn | Network Type: $netType");
遗憾的是,你必须链接到两个外部包才能在你的Flutter项目中获得这个非常基本的功能-但我想目前这是我们拥有的最好的。实际上,我更喜欢数据连接检查器包而不是连接包——但是(在发布这篇文章的时候)前者缺少我从连接包中需要的非常重要的网络识别功能。这就是我(暂时)默认采用这种方法的原因。
使用
dependencies:
connectivity: ^0.4.2
我们从资源处得到的是
import 'package:connectivity/connectivity.dart';
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
未来对我来说没什么问题,我们必须每次都实现它,比如:
check().then((intenet) {
if (intenet != null && intenet) {
// Internet Present Case
}
// No-Internet Case
});
所以为了解决这个问题,我创建了一个类,它接受一个布尔isNetworkPresent参数的函数,就像这样
methodName(bool isNetworkPresent){}
实用工具类是
import 'package:connectivity/connectivity.dart';
class NetworkCheck {
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
dynamic checkInternet(Function func) {
check().then((intenet) {
if (intenet != null && intenet) {
func(true);
}
else{
func(false);
}
});
}
}
并使用连接检查实用程序
fetchPrefrence(bool isNetworkPresent) {
if(isNetworkPresent){
}else{
}
}
我将使用这种语法
NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)
基于这个答案https://stackoverflow.com/a/68436867/10761151
如果你使用dart零安全,你会得到一个错误,
因此,您可以将依赖项data_connection_checker: ^0.3.4更新为internet_connection_checker: ^0.0.1+2
你可以用这个代码
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
class ConnectionUtil {
static final ConnectionUtil _singleton = new ConnectionUtil._internal();
ConnectionUtil._internal();
static ConnectionUtil getInstance() => _singleton;
bool hasConnection = false;
StreamController connectionChangeController = StreamController();
final Connectivity _connectivity = Connectivity();
void initialize() {
_connectivity.onConnectivityChanged.listen(_connectionChange);
}
void _connectionChange(ConnectivityResult result) {
_hasInternetInternetConnection();
}
Stream get connectionChange => connectionChangeController.stream;
Future<bool> _hasInternetInternetConnection() async {
bool previousConnection = hasConnection;
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
// this is the different
if (await InternetConnectionChecker().hasConnection) {
hasConnection = true;
} else {
hasConnection = false;
}
} else {
hasConnection = false;
}
if (previousConnection != hasConnection) {
connectionChangeController.add(hasConnection);
}
return hasConnection;
}
}
在有状态小部件上可以实现此代码
bool hasInterNetConnection = false;
@override
initState() {
ConnectionUtil connectionStatus = ConnectionUtil.getInstance();
connectionStatus.initialize();
connectionStatus.connectionChange.listen(connectionChanged);
super.initState();
}
void connectionChanged(dynamic hasConnection) {
setState(() {
hasInterNetConnection = hasConnection;
});
}