Checking Network Connectivity in Flutter Apps

1.7k
SHARES
7.7k
VIEWS

Today’s tutorial we’ll learn how we can check network connectivity in our flutters apps. Checking network connectivity is very crucial in almost any app. Time comes when we need to check the user’s internet connection and if the user has an internet connection we can proceed further like fetching data over the internet etc, and if the user don’t have an internet connection we simply show him an alert box telling him that you need to turn ON your WiFi or Mobile data.

For this functionality we will use an awesome flutter package Connectivity. This plugin can also distinguish between cellular vs WiFi connection. This plugin works perfectly for both iOS and Android. For this tutorial we’ll check the current network status. So Let’s start

Add Connectivity package in your pubspec.yaml file:

connectivity: ^0.4.2

Now run flutter packages get in your terminal. This command will install this package.

Now in your Dart code, just add the following code:

// Importing Flutter Package
import 'package:connectivity/connectivity.dart';

var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
  print("Connected to Mobile Network");
} else if (connectivityResult == ConnectivityResult.wifi) {
  print("Connected to WiFi");
} else {
  print("Unable to connect. Please Check Internet Connection");
}

You can also listen for network state changes by subscribing to the stream exposed by connectivity plugin. So you will be notified when the network state has changed.

// Importing Flutter Package
import 'package:connectivity/connectivity.dart';


initState() {
  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    print("Connection Status has Changed");
  })
}

dispose() {
  subscription.cancel();
}

I hope the process was easy and straight forward. Happy Coding.!

Best resources to learn Flutter

Leave a Reply

Your email address will not be published. Required fields are marked *