此插件允许Flutter应用程序发现网络连接并相应地进行自我配置。它可以区分蜂窝与WiFi连接。此插件适用于iOS和Android。
添加依赖
dependencies:
connectivity: ^0.4.2
安装
flutter packages get
实例
用于检查当前状态的示例用法:
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
}
您还可以通过订阅连接插件公开的流来侦听网络状态更改:
import 'package:connectivity/connectivity.dart';
initState() {
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Got a new connectivity status!
})
}
// Be sure to cancel subscription after you are done
dispose() {
subscription.cancel();
}