Learn Flutter Step by Step
Posted on
< Previous
ConnectivityPlus is a Flutter package that allows you to check the network connectivity status of your device. It provides an easy-to-use API that allows you to monitor changes in network connectivity and respond to them in your Flutter application.
Add it to your pubspec.yaml file
dependencies:
connectivity_plus: ^3.0.0
Import the ConnectivityPlus package in your Dart file.
import 'package:connectivity_plus/connectivity_plus.dart';
To check the current network connectivity status, you can create an instance of the Connectivity class and use its checkConnectivity() method. This method returns a ConnectivityResult enum value that represents the current connectivity status.
ConnectivityResult connectivityResult = await Connectivity().checkConnectivity(); if (connectivityResult == ConnectivityResult.mobile) {
// Device is connected to a mobile network. }
else if (connectivityResult == ConnectivityResult.wifi) {
// Device is connected to a Wi-Fi network.
} else {
// Device is not connected to any network.
}
To monitor changes in network connectivity, you can create a StreamSubscription and listen to the ConnectivityResult stream. This allows you to respond to changes in network connectivity in real-time.
StreamSubscription subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
if (result == ConnectivityResult.mobile) {
// Device is connected to a mobile network.
}
else if (result == ConnectivityResult.wifi) {
// Device is connected to a Wi-Fi network.
}
else {
// Device is not connected to any network.
} });
Remember to cancel the subscription when it is no longer needed to avoid memory leaks subscription.cancel();
Overall, the ConnectivityPlus package provides an easy way to check and monitor network connectivity status in your Flutter application. It can be used to implement network-dependent functionality and provide a better user experience by handling network connectivity changes gracefully.
Complete Example Code
class _MyHomePageState extends State {
late ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();
late StreamSubscription _connectivitySubscription;
@override
initState() {
super.initState();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
_updateConnectionStatus(result);
// Got a new connectivity status!
});
}
// Be sure to cancel subscription after you are done
@override
dispose() {
_connectivitySubscription.cancel();
super.dispose();
}
Future _updateConnectionStatus(ConnectivityResult result) async {
setState(() {
_connectionStatus = result;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Connectivity example app'),
),
body: Center(
child: Text('Connection Status: ${_connectionStatus.toString()}')),
);
}
}
< Previous