Manage Connectivity In Your Flutter App

Here is the easiest way to manage your app’s connectivity using Flutter and the Connectivity package!

If you have an app that interacts with the outside world, you probably want to make sure that the user is connected before executing any HTTP request!

To accomplish that, we will employ the Connectivity package developed by the Flutter team.

Photo by Thomas Jensen on Unsplash

The Connectivity Package.

This package is rather useful to manage the state of your app’s depending on its current internet connection!

There are two important methods and one getter for the Connectivity class:

onConnectivityChanged: returns a Stream which will allow you to know whenever the connectivity of your app changes.

checkConnectivity: returns the current connectivity of your app.

getWifiName: returns the SSID of the wifi.

Integrate The Connectivity Package In Your App.

Now what we want to do is integrate the package in our app!

What we will try to achieve here is to display a no-connection view whenever the user loses his connection!

Using the stream provided by the Connectivity class, we can know whenever the connection status changes! So based on that, we will push the no-connection view through the Navigator.

To access the navigator regardless of the current stack of navigation, we can use a GlobalKey key that we pass as an argument to the MaterialApp widget. By doing so we can access the current state of the Navigator!

Now let’s code it!

First set up the Navigator GlobalKey:

Now add a listener on the connectivity state stream and make sure to cancel the subscription in the dispose method of your State!

In the callback, we will check the ConnectivityResult, if it is none, we display the no-connection view, and if it is wifi or mobile, we check if the previous result was none and if that’s the case, we push the home view!

Here is the complete code:

If you don’t want to push the no-connection view if the user gets back his connection after x seconds, just use Future.delayed to wait x seconds. Then use the checkConnectivity method to check if he got his connection back or not! To avoid multiple instances of the function use a boolean to know if there is already an instance of the function running! (If you don’t, the no-connection view could push two times (or more) and that can be annoying for the user).

I did not add the NoConnectionView and the HomeView on the gist because that would not be very useful ^^;

You can add a fake button retry for the user on the no-connection view but with the code in the callback, it will automatically push the home view when the user gets back on the internet :)

The End

I hope you enjoyed this article!!

If you did, you may be interested in those other articles that I wrote about Flutter: