Continuously check internet disconnection on Flutter app

nike picture nike · Nov 29, 2018 · Viewed 7k times · Source

I'm creating a mobile application on Flutter and I'm calling REST API's created on Node.js in order to connect and query my oracle DB all the time.

I've use so far the connectivity 0.3.2 in order to check the network connectivity before the async call or login operation. Like the example below :

    checkConnectivity(context) async{

  String connectionStatus;
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  final Connectivity _connectivity = new Connectivity();
  try {
    connectionStatus = (await _connectivity.checkConnectivity()).toString();
    _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      connectionStatus = result.toString();
      //   print(connectionStatus);
    });
  } on PlatformException catch (e) {
    print(e.toString());
    connectionStatus = 'Failed to get connectivity.';
  }
  if(connectionStatus == "ConnectivityResult.none"){
    components.alertPopup(context, "No Internet Connection available" , "Please check your internet connection and try again");}

}

I want to ask if there is any possible way to continuously check internet disconnection in every moment that the user is using the application (even if he is just reading data, without making an API call at all).

In order to notify the user that he is offline with a SnackBar for example.

Answer

Alex Meuer picture Alex Meuer · Nov 29, 2018

You've already written the code to do what you want. You could easily wrap it in a page State or an InheritedWidget or some other managerial class.

final Connectivity _connectivity;
final StreamSubscription<ConnectivityResult> _subscription;

ConstructorForWhateverClassThisIs() {
    _connectivity = new Connectivity();
    _subscription = _connectivity.onConnectivityChanged.listen(onConnectivityChange);
}

void onConnectivityChange(ConnectivityResult result) {
    // TODO: Show snackbar, etc if no connectivity
}

void dispose() {
    // Always remember to cancel your subscriptions when you're done.
    subscription.cancel();
}

According to the documentation, the onConnectivityChanged will be updated with the new result whenever it changes, meaning you can just listen for changes without ever having to manually query it.

Documentation excerpt:

You can also listen for network state changes by subscribing to the stream exposed by connectivity plugin