In this guide, we will learn how to implement the network Connectivity Status in Flutter by using the external package name connectivity_plus. This plugin allows Flutter apps to discover network connectivity. For example, when you are connected or disconnected from wifi. But this package will not tell us if we have or not internet connection. In this example, we are going to show you how to check the internet connection in Flutter. we will learn to check if the device’s internet connection is online or offline, if the device is online, then check if its connection with mobile data, wifi, wired ethernet, or Bluetooth is threatening.
Installation
Run this command:
With Flutter:
$ flutter pub add connectivity_plus
This will add a line like this to your package’s pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
connectivity_plus: ^2.3.0
Import it
Now in our Dart code, we can use:
import 'package:connectivity_plus/connectivity_plus.dart';
Let’s take an example of how we can implement the network Connectivity Status in our flutter application.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
class ConnectivityScreen extends StatefulWidget {
const ConnectivityScreen({Key? key}) : super(key: key);
@override
State<ConnectivityScreen> createState() => _ConnectivityScreenState();
}
class _ConnectivityScreenState extends State<ConnectivityScreen> {
String status = '';
late StreamSubscription streamSubscription;
Future<void> checkConnectivity() async {
var result = await Connectivity().checkConnectivity();
if (result == ConnectivityResult.mobile) {
setState(() {
status = 'Mobile Network Connected';
});
} else if (result == ConnectivityResult.wifi) {
setState(() {
status = 'Wifi NetWork Connected';
});
} else {
setState(() {
status = 'No Device Connected';
});
}
}
@override
void initState() {
checkConnectivity();
streamSubscription = Connectivity().onConnectivityChanged.listen((event) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.teal,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
content: Container(
margin: const EdgeInsets.all(10),
child: Text(
'Connectivity Changed to ' + event.name,
textAlign: TextAlign.center,
)),
),
);
setState(() {
status = event.name;
});
});
super.initState();
}
@override
void dispose() {
streamSubscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Connectivity in Flutter'),
centerTitle: true,
),
body: Center(
child: Text(
"Status " + status,
style: Theme.of(context)
.textTheme
.headline4!
.copyWith(fontWeight: FontWeight.bold, color: Colors.black),
),
),
);
}
}
Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:
Get the full snippet from here