Network Connectivity in Flutter

Jamie
Jamie Dev
Published in
4 min readDec 24, 2020

A Quick article on how to check the network connectivity in Flutter. We will see three ways to check the network connectivity in Flutter.

Network Connectivity in Flutter

Video Tutorial

Network Connectivity in Flutter

Add Dependency

We are gonna use the below dependency to achieve this.

connectivity 2.0.2
provider 4.3.2+3

https://pub.dev/packages/connectivity

Method 1

I will start with the code itself

String _networkStatus1 = '';

Connectivity connectivity = Connectivity();

void checkConnectivity1() async {
var connectivityResult = await connectivity.checkConnectivity();
var conn = getConnectionValue(connectivityResult);
setState(() {
_networkStatus1 = 'Check Connection:: ' + conn;
});
}

// Method to convert the connectivity to a string value
String getConnectionValue(var connectivityResult) {
String status = '';
switch (connectivityResult) {
case ConnectivityResult.mobile:
status = 'Mobile';
break;
case ConnectivityResult.wifi:
status = 'Wi-Fi';
break;
case ConnectivityResult.none:
status = 'None';
break;
default:
status = 'None';
break;
}
return status;
}

This is really simple.

We create a Connectivity object and call checkConnectivity on it and based on the return value we determine if it is connected to WiFi, Mobile or not connected.

Method 2

Using Subscription, we can subscribe to the network change events.

String _networkStatus2 = '';

Connectivity connectivity = Connectivity();
StreamSubscription<ConnectivityResult> subscription;

@override
void initState() {
super.initState();
checkConnectivity2();
}

// Method2 - Using Subscription
void checkConnectivity2() async {
// Subscribe to the connectivity change
subscription =
connectivity.onConnectivityChanged.listen(
(ConnectivityResult result) {
var conn = getConnectionValue(result);
setState(() {
_networkStatus2 = '<Subscription> :: ' + conn;
});
});
}

Here is another simple solution using subscription.

We create a Stream Subscription to listen to it and then we use the same getConnectionValue on the Method 1 to determine the connectivity.

The ‘onConnectivityChanged’ is the stream we are listening to.

Method 3

What if you want to listen to network changes through out the app
and widgets gets automatically updated when the network changes..
For that we use the StreamProvider in the root level of the app
to propagate changes through out the app. We will be using provider for that.
Let’s create a new class to manage it.
Go to the root widget from where you want to listen to changes
Let’s open the main.dart file where we have added this class.
The widget will be updated whenever the connection changes…

Create a new Class Connectivity service. Create a constructor, add the value from the Connection change to the Stream Provider, which will cause the main widget to update.

import 'dart:async';
import 'package:connectivity/connectivity.dart';

class ConnectivityService {
//
StreamController<ConnectivityResult> connectionStatusController =
StreamController<ConnectivityResult>();
// Stream is like a pipe, you add the changes to the pipe, it will
// come out on the other side.
// Create the Constructor

ConnectivityService() {
// Subscribe to the connectivity changed stream
Connectivity().onConnectivityChanged.listen(
(ConnectivityResult result) {
connectionStatusController.add(result);
});
}
}
void checkConnectivity3() async {
var connectivityResult = Provider.of<ConnectivityResult>. (context);
var conn = getConnectionValue(connectivityResult);
setState(() {
_networkStatus3 = '<Provider> :: ' + conn;
});
}

main.dart will look like this

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'widgets/Connectivity/ConnectivityDemo.dart';
import 'widgets/Connectivity/ConnectivityService.dart';
import 'package:provider/provider.dart';

void main() {
runApp(
new HomeApp(),
);
}

// Wrap main widget inside the StreamProvider
class HomeApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamProvider<ConnectivityResult>(
builder: (context) => ConnectivityService().connectionStatusController,
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Tutorials',
home: new ConnectivityDemo(),
),
);
}
}

Complete Code

import 'dart:async';
import 'package:connectivity/connectivity.dart';

class ConnectivityService {
//
StreamController<ConnectivityResult> connectionStatusController =
StreamController<ConnectivityResult>();
// Stream is like a pipe, you add the changes to the pipe, it will come
// out on the other side.
// Create the Constructor

ConnectivityService() {
// Subscribe to the connectivity changed stream

Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
connectionStatusController.add(result);
});
}
}


import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:provider/provider.dart';

class ConnectivityDemo extends StatefulWidget {
ConnectivityDemo() : super();

final String title = "Connectivity Demo";

@override
ConnectivityDemoState createState() => ConnectivityDemoState();
}

class ConnectivityDemoState extends State<ConnectivityDemo> {
// In this video we will see 3 different ways to check network connectivity in Flutter.
// So Let's Start...
// First add the plugin..go to pubspec.yaml file and add.
// The Plugin link is available in the description.

// To keep it simple lets create 3 different varaibles to identify each
// import the needed pacakges

String _networkStatus1 = '';
String _networkStatus2 = '';
String _networkStatus3 = '';

Connectivity connectivity = Connectivity();
StreamSubscription<ConnectivityResult> subscription;

@override
void initState() {
super.initState();
checkConnectivity2();
}

// Method1
void checkConnectivity1() async {
var connectivityResult = await connectivity.checkConnectivity();
var conn = getConnectionValue(connectivityResult);
setState(() {
_networkStatus1 = 'Check Connection:: ' + conn;
});
}

// Method2 - Using Subscription
void checkConnectivity2() async {
// Subscribe to the connectivity change
subscription =
connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
var conn = getConnectionValue(result);
setState(() {
_networkStatus2 = '<Subscription> :: ' + conn;
});
});
}

// Method3 - Using Providers

void checkConnectivity3() async {
var connectivityResult = Provider.of<ConnectivityResult>(context);
var conn = getConnectionValue(connectivityResult);
setState(() {
_networkStatus3 = '<Provider> :: ' + conn;
});
}

// Method to convert the connectivity to a string value
String getConnectionValue(var connectivityResult) {
String status = '';
switch (connectivityResult) {
case ConnectivityResult.mobile:
status = 'Mobile';
break;
case ConnectivityResult.wifi:
status = 'Wi-Fi';
break;
case ConnectivityResult.none:
status = 'None';
break;
default:
status = 'None';
break;
}
return status;
}

@override
Widget build(BuildContext context) {
// Update widget whenever connection changes
checkConnectivity3();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(_networkStatus1),
SizedBox(height: 20.0),
OutlineButton(
child: Text('Check Connection'),
onPressed: () {
checkConnectivity1();
},
),
SizedBox(height: 20.0),
// This string will be updated automatically when the
// connection changes
Text(_networkStatus2),
SizedBox(height: 20.0),
Text(_networkStatus3),
SizedBox(height: 20.0),
],
),
),
);
}
}

That’s it.

Please leave your valuable comments below this post.

Please clap if this article is useful for you.

Thanks for reading.

--

--

Jamie
Jamie Dev

Flutter, React Native, Android, iOS App developer.