Internet Connectivity check-in Flutter

Hi, Flutter developer in this blog we shall learn how to check the connection status inside our flutter app. Most of the apps use internet connectivity to request the data or perform crud operations. If the connections are not available, it becomes necessary to abort the request and display the error message to the user about the issue.

In this blog, we shall build a simple app that will help us to identify the connection type and in case there is no connection then we will display the error screen.

DevBytes is a news app for programmers, developers, coders, and any enthusiast learner who wants to know about what is happening in the developer community.
We select the latest news from authentic sources, tech news blogs, and the community and summarize them in less than 64 words. Wherever needed, we provide the programming code snippets too for your easy reference.

At DevBytes, you get all the content in one place — JavaScript, Node.js, Python, React, Angular, Go Lang, GitHub, algorithms, web3, CLI, CSS, web development tools, FAANG news, Machine Learning and even startups. As a bonus, we also cover cryptos, blockchain, and NFTs.

Key features of the app:
We send you a daily briefing, customized as per your needs and at a time decided by you.

No frills, no fancy notifications, and no login needed. You don’t have to worry about privacy, we don’t collect any data.

If you know how to code, you will get better. If you are learning to code, this is a place for you. Byte-sized news for the busy developers and coders.

Get updated with the latest news updates and grow your career. It is a must-have app for any developer or professional working in the technology sector.

What do we cover?
JavaScript- We curate relevant news and tutorials from top JavaScript blogs to apprise you of the latest developments in the JavaScript community.

Node.js- Learn what is happening in the Node.js community by reading summaries of top blogs and other news sources.

HTML- HyperText Markup Language (HTML) is the standard markup language for creating web applications. And at DevBytes, you will get the latest news about HTML5 in a concise manner.

Python- For anyone interested in Data Sciences and AI, understanding Python is the first step. And we help you understand what is happening in the community of Python developers. You will also get to know about the latest news from the official blog of the community.

React- The developer world is transitioning towards web3 and React is considered a path to make a mark in this new frontier. You can read all about hacks and tricks to master React on DevBytes.

GitHub- GitHub is one of the most famous platforms to host open-source projects. And with DevBytes, you can get to know what is happening in the GitHub community.

Machine Learning- Learn what is happening in the world of Machine learning on DevBytes. We curate the most interesting blogs and summarize them in a byte-sized manner.

Cryptocurrency and NFTs- DevBytes is a must-have app for cryptocurrency and NFTs enthusiasts. We provide byte-sized content on how to create NFTs, what is happening in the crypto world, and trending web3 projects.

Package used:

connectivity_plus is a plugin that allows flutter apps to discover internet connectivity.

ConnectivityResult

It is an enum provided by the connectivity_package , that helps us to set the output of the connectivity, and later we can use the enum value to change the UI stuff.

Connectivity
  1. This class helps us to distinguish between the wifi network and mobile network.
  2. It constructs the singleton instance of the Connectivity .
  3. It provides us onConnectivityChanged stream that we return the Stream of ConnectivityResult . It provides us with a live update about the connection status when the listener is added.
  4. checkConnectivity is a method that returns a Future of ConnectivityResult . It fires connectivity state only once while onConnectivityChanged streams fire the state live.

Using onConnectivityChanged method

checkConnectivity returns a Future of ConnectivityResult . We can use the result of it to display the message to the user or change the UI accordingly.

Initialize the connectivity object:

Connectivity connectivity = Connectivity();MaterialButton(
color: Colors.blue,
onPressed: () async {
await connectivity.checkConnectivity();
},
child: const Text("Check Connection"),
),

Display snack bar:

We can use the then method to get the value of the future and call the snack bar inside it.

We have also implemented the condition that if there is no connection then the color of the snack bar will be red else it will be green.

onPressed: () async {
await connectivity.checkConnectivity().then(
(value) => ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: value == ConnectivityResult.none
? Colors.red
: Colors.green,
content: Text(
value.name + " Connection available",
),
),
),
);

Demo:

Using onConnectivityChanged stream

Create a stateful widget and initialize the ConnectivityResult and Connectivity objects.

ConnectivityResult connectivityResult = ConnectivityResult.none;
Connectivity connectivity = Connectivity();

Inside the initiState method, we can call the stream connectivity.onConnectivityChanged with the listener, every time the connection changes the listener updates the result.

@override
void initState() {
connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
setState(() {
connectivityResult = result;
});
});
super.initState();
}

Use the setState method to update the connectivityResult object.

On the screen, we will add the test message to change the UI accordingly. We will create a method connectivityCheck that returns the String based on the ConnectivityResult .

String connectivityCheck(ConnectivityResult result) {
if (result == ConnectivityResult.wifi) {
return "You are now connected to wifi";
} else if (result == ConnectivityResult.mobile) {
return "You are now connected to mobile data";
} else if (result == ConnectivityResult.ethernet) {
return "You are now connected to ethernet";
} else if (result == ConnectivityResult.bluetooth) {
return "You are now connected to bluetooth";
} else if (result == ConnectivityResult.none) {
return "No connection available";
} else {
return "No Connection!!";
}
}

UI:

When the ConnectivityResult is none the color of appbar will be red else it will be green.

Scaffold(
appBar: AppBar(
backgroundColor: connectivityResult == ConnectivityResult.none
? Colors.red
: Colors.green,
title: const Text("Connectivity check"),
),
body: Center(
child: Text(connectivityCheck(connectivityResult)),
),
)

In the Text widget, we will call the connectivityCheck
method that will return the String based on the connectivityResult .

Full code:

import 'dart:developer';import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ConnectivityResult connectivityResult = ConnectivityResult.none;
Connectivity connectivity = Connectivity();
@override
void initState() {
connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
setState(() {
connectivityResult = result;
});
log(result.name);
});
super.initState();
}
String connectivityCheck(ConnectivityResult result) {
if (result == ConnectivityResult.wifi) {
return "You are now connected to wifi";
} else if (result == ConnectivityResult.mobile) {
return "You are now connected to mobile data";
} else if (result == ConnectivityResult.ethernet) {
return "You are now connected to ethernet";
} else if (result == ConnectivityResult.bluetooth) {
return "You are now connected to bluetooth";
} else if (result == ConnectivityResult.none) {
return "No connection available";
} else {
return "No Connection!!";
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: connectivityResult == ConnectivityResult.none
? Colors.red
: Colors.green,
title: const Text("Connectivity check"),
),
body: Center(
child: Text(connectivityCheck(connectivityResult)),
),
),
);
}
}

Using StreamBuilder

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Connectivity connectivity = Connectivity();
String connectivityCheck(ConnectivityResult? result) {
if (result == ConnectivityResult.wifi) {
return "You are now connected to wifi";
} else if (result == ConnectivityResult.mobile) {
return "You are now connected to mobile data";
} else if (result == ConnectivityResult.ethernet) {
return "You are now connected to ethernet";
} else if (result == ConnectivityResult.bluetooth) {
return "You are now connected to bluetooth";
} else if (result == ConnectivityResult.none) {
return "No connection available";
} else {
return "No Connection!!";
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: StreamBuilder<ConnectivityResult>(
stream: connectivity.onConnectivityChanged,
builder: (context, snapshot) {
return Scaffold(
appBar: AppBar(
backgroundColor: snapshot.data == ConnectivityResult.none
? Colors.red
: Colors.green,
title: const Text("Connectivity check"),
),
body: Center(
child: Text(connectivityCheck(snapshot.data)),
),
);
}),
);
}
}

Demo:

Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

If we got something wrong? Let me know in the comments. we would love to improve.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store