需要的第三方插件
- connectivity_plus: ^5.0.1
- internet_connection_checker: ^1.0.0+1
实现监听
首先有个网络监听类,处理一些网络监听等逻辑
class NetworkMonitor {
/// 返回网络情况,判断网络是否能用
Future<bool> isNetworkConnected({List<String>? addressList})async{
List<AddressCheckOptions> adds;
if(addressList==null){
adds=[AddressCheckOptions(hostname:'Your hostname',port:80,AddressCheckOptions(hostname:'Your hostname'))]
}else{
adds=addressList.map((e)=>AddressCheckOptions(address:InternetAddress(e))).toList();
}
final checker = InternetConnectionChecker()..addresses=adds;
final isConnected = await checker.hasConnection;
return isConnected;
}
}
页面进行网络监听
/// 网络监听
ConnectivityResult _networkConnectionStatus=ConnectivityResult.none;
/// 网络连接
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
/// 网络是否通畅
bool _isConnected = false;
void initState(){
super.initState();
_init();
_connectivitySubscription=_connectivity.onConnectivityChanged.listen(_updateConnectStatus);
}
Future<void> _init()aysnc{
final isConnect = await NetworkMonitor().isNetworkConnected();
setState((){
_isConnected=isConnect;
});
}
Future<void> _updateConnectStatus(ConnectivityResult result)async{
setState((){
_netWorkConnectionStatus=result;
});
if(result!=ConnectivityResult.none){
final isConnect = await NetworkMonitor().isNetworkConnected();
setState((){
_isConnected = isConnect;
});
}
}
/// 页面
Container(
child: (_networkConnectionStatus!=ConnectivityResult.none&&_isConnected)||_isConnected?Qrcode():WifiOff()
)