首页 > 解决方案 > 使用连接加包(颤振)监听互联网连接

问题描述

我想显示一个快餐栏来通知用户他们离线。到目前为止,下面的代码似乎可以正常工作,但是我无法让它正常工作,因为离线和在线小吃店都一个接一个地显示。我在 initstate 中使用以下内容。请指教。谢谢

Connectivity _connectivity = Connectivity();
_connectionChangeStream = _connectivity.onConnectivityChanged.listen((event) {

if (event == ConnectivityResult.none) {
showOfflineSnackBar(context);
_internetLost = true;
setState(() {

});
}  if (_internetLost == true ) {
showOnlineSnackBar(context);
_internetLost = false;
setState(() {

});
    }
});

showOfflineSnackBar(context)  {
final snackBar = SnackBar(
backgroundColor: Colors.redAccent,
content: const Text('You are offline!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
},
),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}

标签: flutter

解决方案


连接插件的问题它不检查互联网连接意味着,您可能连接到 wifi 但没有互联网,移动数据也是如此,它只是检查 wifi 或移动数据是否打开或关闭,所以一点点搜索我发现了多个代码并在我的应用程序中实现,它将监听互联网连接

安装这些包并导入包

连通性

吐司

数据连接检查器

初始化变量

  var subscription;
  var connectionStatus;
  String _connectionStatus = 'Unknown';
  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

用于检查连接的 InitState 和函数

 @override
  void initState() {
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    checkInternetConnectivity();
    super.initState();

  }

  Future<bool> checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Mobile data detected & internet connection confirmed.
        return Fluttertoast.showToast(
            msg: "Connected to Mobile Network",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return true;
      } else {
        // Mobile data detected but no internet connection found.
        return Fluttertoast.showToast(
            msg: "Mobile data detected but no internet connection found",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return false;
      }
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a WIFI network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Wifi detected & internet connection confirmed.
        return Fluttertoast.showToast(
            msg: "Connected to WIFI Network",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return true;
      } else {
        // Wifi detected but no internet connection found.
        return Fluttertoast.showToast(
            msg: "Wifi detected but no internet connection found.",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return false;
      }
    } else {
      // Neither mobile data or WIFI detected, not internet connection found.
      return Fluttertoast.showToast(
          msg: "No Internet connection found",
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIosWeb: 1,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0
      );
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // 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);
  }

//Constantly check for the status of the connection

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    if(result==ConnectivityResult.mobile)
      {
        if (await DataConnectionChecker().hasConnection) {
          // Mobile data detected & internet connection confirmed.
          return Fluttertoast.showToast(
              msg: "Connected to Mobile Network",
              toastLength: Toast.LENGTH_SHORT,
              timeInSecForIosWeb: 1,
              gravity: ToastGravity.BOTTOM,
              backgroundColor: Colors.green,
              textColor: Colors.white,
              fontSize: 16.0
          );
          return true;
        } else {
          // Mobile data detected but no internet connection found.
          return Fluttertoast.showToast(
              msg: "Mobile data detected but no internet connection found",
              toastLength: Toast.LENGTH_SHORT,
              timeInSecForIosWeb: 1,
              gravity: ToastGravity.BOTTOM,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0
          );
          return false;
        }
      }
    else if(result==ConnectivityResult.mobile){
      if (await DataConnectionChecker().hasConnection) {
        // Wifi detected & internet connection confirmed.
        return Fluttertoast.showToast(
            msg: "Connected to WIFI Network",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.green,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return true;
      } else {
        // Wifi detected but no internet connection found.
        return Fluttertoast.showToast(
            msg: "Wifi detected but no internet connection found.",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return false;
      }
    }
    else if(result==ConnectivityResult.none){
      if (await DataConnectionChecker().hasConnection) {
        // Wifi detected & internet connection confirmed.
        return Fluttertoast.showToast(
            msg: "No Internet connection found",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return true;
      } else {
        // Wifi detected but no internet connection found.
        return Fluttertoast.showToast(
            msg: "No Internet connection found",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 1,
            gravity: ToastGravity.BOTTOM,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0
        );
        return false;
      }
    }

  }
  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

推荐阅读