connectivity偵測網路狀態
判斷當前是Wifi或是一般手機網路
在安卓系統上, 不保證是否一定有連上網路
Note that on Android, this does not guarantee connection to Internet.
程式部分 在main.dart裡
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ConnectivityManager().init();
await UserDefault().init();
// await PushNotificationManager.init();
runApp(MyApp());
}
接著建立ConnectivityManager封裝一次
並在onConnectivityChanged裡面寫handler,
這邊也用到了GetX snackbar 作通知.
class ConnectivityManager {
final Connectivity _connectivity = Connectivity();
init() async {
//App launch check once
final reslut = await _connectivity.checkConnectivity();
resultHandler(reslut);
_connectivity.onConnectivityChanged.listen((result) {
//At app using, if network changed
resultHandler(result);
});
}
resultHandler(ConnectivityResult result) {
if (result == ConnectivityResult.none) {
Future.delayed(Duration(seconds: 1)).then((value) {
Get.snackbar(
"當前狀態無網路",
"請檢查網路連線",
duration: Duration(days: 1),
icon: Icon(Icons.signal_wifi_bad),
);
});
} else {
if (Get.isSnackbarOpen != null) {
if (Get.isSnackbarOpen!) Get.back();
}
}
}
}
效果如下
下一篇將為大家介紹 Socket.io