iT邦幫忙

2024 iThome 鐵人賽

DAY 17
0
Mobile Development

畢業專題拯救計畫系列 第 17

Flutter中的網路檢測器--connectivity_plus

  • 分享至 

  • xImage
  •  

connectivity_plus 是 Flutter 社區中常用的一個插件,它用於檢測設備的網絡連接狀態。無論設備是通過 Wi-Fi、移動數據還是根本沒有連接到網絡,connectivity_plus 插件都能幫助你獲取當前的網絡狀態。

添加到 pubspec.yaml

要使用這個插件,需要在 pubspec.yaml 文件中添加 dependencies:

dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^6.0.5

檢查當前的網絡連接狀態

ConnectivityResult result = await _connectivity.checkConnectivity();

根據連接結果進行處理

可以自己設定列印的文字

if (result == ConnectivityResult.wifi) {
  print('Connected to Wi-Fi');
} else if (result == ConnectivityResult.mobile) {
  print('Connected to Mobile Data');
} else if (result == ConnectivityResult.none) {
  print('No Internet Connection');
}

監聽網絡狀態變更

_connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
  if (result == ConnectivityResult.wifi) {
    print('Switched to Wi-Fi');
  } else if (result == ConnectivityResult.mobile) {
    print('Switched to Mobile Data');
  } else if (result == ConnectivityResult.none) {
    print('Lost Internet Connection');
  }
}

如果有連上 Wifi 它會長這樣
https://ithelp.ithome.com.tw/upload/images/20240903/20163322nKDof0tJCg.png
https://ithelp.ithome.com.tw/upload/images/20240903/20163322xtrqrS5Nug.png
當我們切斷 Wifi 只開行動熱點
https://ithelp.ithome.com.tw/upload/images/20240903/201633228j8SUZM0ia.png
會出現 Connected to Mobile Network
https://ithelp.ithome.com.tw/upload/images/20240903/20163322ctg1L5UuCH.png
當我們把 Wifi 與行動熱點都切斷
https://ithelp.ithome.com.tw/upload/images/20240903/201633220XDJD2ONNL.png
會出現 No Internet Connection
https://ithelp.ithome.com.tw/upload/images/20240903/20163322sSVJgwQq8v.png
我們明天見~


上一篇
Flutter中的Plugin--path_provider
下一篇
Flutter中的動畫--Implicit Animations
系列文
畢業專題拯救計畫22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言