How to Check Network Connectivity Status in Flutter — Connectivity_plus Package

Fernando Putra
4 min readApr 16, 2022

--

Most mobile applications require a network connection via WiFi or mobile data to fetch data. But frequently, when fetching data, it loads continuously without providing any information, although there is a connectivity problem. As a result, we kept waiting and thought it was still fetching data.

Therefore, checking the user’s connectivity status is crucial before proceeding with actions reliant on the network. Gratefully, there is a package that allows us to discover the network connectivity status named connectivity_plus package.

In this article, we’ll learn to use the connectivity_plus package to check whether the device is connected to the network. If not, we’ll show a network error dialog.

1. Setting up The Project

First, we must add the required dependency, the connectivity_plus package to your pubspec.yaml file.

dependencies:
connectivity_plus: ^2.3.0

Or run the following command:

$ flutter pub add connectivity_plus
// This will add the same line to your package's pubspec.yaml

Next, we need to add an image for the dialog to the project.

  1. Create an assets/images folder
  2. Add the image to the folder. You can download the image here
  3. Register the folder in pubspec.yaml
flutter:
assets:
- assets/images/

Lastly, replace the content of your main.dart file with the following code, and we’re all set.

2. Check The User’s Connectivity Status

To check the user’s connectivity status, create an instance of Connectivity and make a call to the checkConnectivity() method. For example:

var connectivityResult = await (Connectivity().checkConnectivity());

This method returns ConnectivityResult enum whose values are:

  • wifi: Connected to a WiFi network.
  • mobile: Connected to a mobile network.
  • none: Not connected to any network.

Create a new file called check_connection_page.dart in the lib folder of your project, add the following code:

import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

class CheckConnectionPage extends StatelessWidget {
const CheckConnectionPage({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Check Connection Page")),
body: SafeArea(
child: Center(
child: ElevatedButton(
child: const Text("Check Connection"),
onPressed: () async {
final connectivityResult =
await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text(
'You\'re not connected to a network')
));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You\'re connected to a ${connectivityResult.name} network')
));
}
},
),
),
),
);
}
}

The preview will look like this:

When you press the Check Location button, it will initially check the connectivity status of the device. If the device is not connected to the internet, a snack bar with the message “You are not connected to the network.” will appear. Otherwise, a snack bar with a device connectivity status message will appear.

3. Show a Network Error Dialog if There Is No Connection

To show a network error dialog if there is no connection, create a NetworkErrorDialog widget with a function as a parameter in the constructor. This widget returns an AlertDialog widget.

class NetworkErrorDialog extends StatelessWidget {
const NetworkErrorDialog({Key? key, this.onPressed}) : super(key: key);
final Function()? onPressed;

@override
Widget build(BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
content: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 200,
child: Image.asset('assets/images/no_connection.png')
),
const SizedBox(height: 32),
const Text(
"Whoops!",
style: TextStyle(fontSize: 16,
fontWeight: FontWeight.w700),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
const Text(
"No internet connection found.",
style: TextStyle(fontSize: 14,
fontWeight: FontWeight.w500),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
const Text(
"Check your connection and try again.",
style: TextStyle(fontSize: 12),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
child: const Text("Try Again"),
onPressed: onPressed,
)
],
),
);
}
}

Show the dialog by implementing the NetworkErrorWidget widget in the ConnectivityResult.none statement:

// ...
child: ElevatedButton(
child: const Text("Check Connection"),
onPressed: () async {
final connectivityResult =
await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
showDialog(
barrierDismissible: false,
context: context,
builder: (_) => const NetworkErrorDialog(),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You\'re connected to a ${connectivityResult.name} network')));
}
},
),

Then, we pass the function to the NetworkErrorDialog widget to recheck the connectivity status when the user presses the Try Again button

builder: (_) => NetworkErrorDialog(
onPressed: () async {
final connectivityResult =
await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please turn on your wifi or mobile data')));
} else {
Navigator.pop(context);
}
},
),

After all, this is how the check_connection_page.dart looks.

The final result will look like this:

Congrats, you have learned how to check the user’s connectivity state in your Flutter project. I hope this article helped you to get started with the connectivity_plus package in Flutter 😁.

You can access the repository of this article here on GitHub.

Thank you for reading! If you found this article helpful, kindly share it with your friends and follow my profile for future updates. Your support is much appreciated! PS: It would mean even more if you donate a pizza 🍕 here. ✌️

--

--