Detecting Offline Status in Flutter: A Guide to Network Connectivity Monitoring
In Flutter, you can detect if a phone is offline by using the connectivity_plus
package, which provides a platform-agnostic way to check the network connectivity status. Here's a step-by-step guide on how to achieve this:
Add Dependency
First, you need to add the connectivity_plus
package to your pubspec.yaml
file. You can do this by running the command
flutter pub add connectivity_plus
Import Package
Import the connectivity_plus
package in the file where you want to check for network connectivity:
import 'package:connectivity_plus/connectivity_plus.dart';
Check Connectivity Status
You can listen for network state changes by subscribing to the stream exposed by connectivity_plus
plugin. Here's how you can do it:
// The subscription provides events to the listener, and holds
// the callbacks used to handle the events
StreamSubscription<ConnectivityResult>? subscription;
//Connection status check result.
ConnectivityResult? connectivityResult;
@override
initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
setState(() {
connectivityResult = result;
});
});
}
In the method initState
, listen if the device is offline by using the onConnectivityChanged
method provided by the connectivity_plus
package. It returns true
if the connectivity result is none
, indicating that the device is offline.
Usage
You can use the result fromconnectivityResult
in your Flutter app wherever you need to check if the device is offline. For example:
Text((connectivityResult == ConnectivityResult.none)
? 'Device is Offline'
: "Device is Online"))
This approach allows you to detect whether a device is offline in your Flutter app. You can then handle the offline state based on your application’s requirements, such as displaying a message to the user or disabling certain features that require an internet connection.
Remember to handle errors gracefully, as network connectivity can change dynamically, and there might be exceptions during the connectivity check process. Also, cancel the subscription after use.
@override
dispose() {
subscription!.cancel();
super.dispose();
}
Happy coding!
👏🏽 👏🏽 Give this story CLAPS
👉🏽 Subscribe for upcoming articles
💰 Access Free Mobile Development tutorials
🔔 Follow for more
See you on next article 👋