美文网首页
flutter 网络是否可用,监听网络变化

flutter 网络是否可用,监听网络变化

作者: 张漂亮1号 | 来源:发表于2020-02-01 19:22 被阅读0次
StreamSubscription<ConnectivityResult> _connectivitySubscription;
//网络初始状态
connectivityInitState() {
  _connectivitySubscription =
      Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    print('=======' + result.toString());
    if (result == ConnectivityResult.none) {
      UiUtil.showToast('网络已断开,请链接网络!');
      isConnectServerAvailable = false;
      StoreState.status = getXMMPConnectionStatus('DISCONNECTING');
      ConnectRefreshAction action = ConnectRefreshAction(StoreState.status);
      StoreState.connectStore.dispatch(action);
    } else {
      //UiUtil.showToast('链接中...');
      //每次网络变化都会检查网络
      checkClientState();
    }
    //这个位置不能动
    networkStatus = result;
  });
}

//网络结束监听
connectivityDispose() {
  _connectivitySubscription.cancel();
}

//网络进行监听
Future<Null> initConnectivity() async {
  String connectionStatus;
  //平台消息可能会失败,因此我们使用Try/Catch PlatformException。
  try {
    connectionStatus = (await Connectivity().checkConnectivity()).toString();
    if (connectionStatus == ConnectivityResult.mobile) {
    } else if (connectionStatus == ConnectivityResult.wifi) {}
  } on PlatformException catch (e) {
    print(e.toString());
    connectionStatus = 'Failed to get connectivity.';
  }
}
image

更多详解:
喜欢可以加Q群号:913934649,点赞,评论;

简书: https://www.jianshu.com/u/88db5f15770d

csdn:https://me.csdn.net/beyondforme

掘金:https://juejin.im/user/5e09a9e86fb9a016271294a7

相关文章

网友评论

      本文标题:flutter 网络是否可用,监听网络变化

      本文链接:https://www.haomeiwen.com/subject/jgvxxhtx.html