0

I would like to display a snackbar to notify the user that they are offline. so far the code below seems to be working however, i am not able to have it work correctly as both offline and online snackbars display after one another. I am using the below in initstate. Please advise. Thank you

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);
}
Sam
  • 41
  • 4
  • What do you want to achieve? and what do you mean by `i am not able to have it work correctly as both offline and online snackbars display after one another.` can you elaborate more on this? – HeIsDying Aug 11 '21 at 03:17

1 Answers1

0

The problem with the connectivy plugins it doesn't check for internetconnection means,you may be connected to a wifi but there will no internet,same goes with mobile data,it just check if wifi or mobile data is on or off,so little bit searching i have found multiple codes and implemented in my app,it will listen for the internet connection

Install these packages and import the packages

connectivity

fluttertoast:

data_connection_checker:

Initialize variables

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

InitState and functions for checking connections

 @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();
  }
Abhijith
  • 2,227
  • 2
  • 15
  • 39
  • also refer this https://stackoverflow.com/questions/49648022/check-whether-there-is-an-internet-connection-available-on-flutter-app – Abhijith Aug 11 '21 at 07:56
  • Hi. Thank you for your help. How would i notify only when the internet is back online after an internet connection is lost. At this point of time, the user is being notified everytime the state is initiated. Thank you for your help once again – Sam Aug 13 '21 at 02:12
  • I think this code done that,Try test like this create hotspot with another phone and don't enable internet it then try run the app after that enable internet,it always check for connection state changes,if not you can run the code with in every 1 minute kind like that@Sam – Abhijith Aug 13 '21 at 04:35