connectivity_plus 雖然支援六平台,但使用上情境還是以mobile為主,桌機不太可能一直切換連線方式。
在手機app 的issue 有很多都是切換連線方式產生的,所以要知道手機裝置用什麼方式連線是很重要的。
connectivity_plus 可以分辨行動 網路連接 和 WiFi 連接
import 'package:connectivity_plus/connectivity_plus.dart';
final 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.
} else if (connectivityResult == ConnectivityResult.ethernet) {
// I am connected to a ethernet network.
} else if (connectivityResult == ConnectivityResult.vpn) {
// I am connected to a vpn network.
// Note for iOS and macOS:
// There is no separate network interface type for [vpn].
// It returns [other] on any device (also simulator)
} else if (connectivityResult == ConnectivityResult.bluetooth) {
// I am connected to a bluetooth.
} else if (connectivityResult == ConnectivityResult.other) {
// I am connected to a network which is not in the above mentioned networks.
} else if (connectivityResult == ConnectivityResult.none) {
// I am not connected to any network.
}
直接在 pubspec.yaml 加上 connectivity_plus: ^4.0.2 ,然後pub get
dependencies:
connectivity_plus: ^4.0.2
在 /lib/main.dart 加入 程式
import 'package:connectivity_plus/connectivity_plus.dart';
宣告變數和初始化
class _MyHomePageState extends State<MyHomePage> {
ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
...
@override
void initState() {
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}
@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}
Future<void> initConnectivity() async {
late ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
log('Couldn\'t check connectivity status', error: e);
return;
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return Future.value(null);
}
return _updateConnectionStatus(result);
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
setState(() {
_connectionStatus = result;
});
}
...
_infoTile('Day16 Connection Status:',_connectionStatus.toString()),
行動網路
wifi
使用起來可以即時抓取網路的變化狀態也簡單好用