The connectivity package is this week’s ‘package of the week’. It lets you easily check if there’s a connection or not, giving both you but also possibly the user better feedback on what’s going on. Let’s go hands-on and give it a spin!
Don’t you hate it when you get this ‘something went wrong’ error without knowing what actually went wrong? We’ve all been there, but probably have all done it in our own apps as well: we try to get away with some basic error handling, just making sure we let the user know there was an error without actually telling them what the problem was. They might try again, hoping the next request will succeed, but it might as well be hopeless.
There’s no surprise in telling you this is a bad user experience, and luckily the connectivity package helps us to improve our app’s UX! A package that helps us to check whether the device has a connection to a cellular (mobile) network, wifi, or none at all! By using this package, we can improve error handling, telling the user they’re not connected to any network for example.
Checking our connection
Cool, so first things first, let’s put the package in our pubspec.yaml
file:
connectivity_plus: 1.0.3
Now run flutter pub get
and we’re ready to go!
We have 2 ways of checking the connection: by using a Future or a Stream. Let’s start by using the Future here and simply getting the current connection state by using async
/await
:
As you can see, we simply go through the code from top to bottom using async
/await
and can check if the device is connected to wifi, mobile, or doesn’t have an active connection at all.
Cool! But what if we’d like to observe changes in our connection?