Enhancing App Connectivity with Connectivity Plugin for Flutter
Published on by Flutter News Hub
The Connectivity plugin empowers Flutter applications with the ability to detect network connectivity status and adapt their functionality accordingly. It can differentiate between cellular and WiFi connections, providing valuable insights for developers.
Usage Guidelines
Checking Current Connectivity Status:
import 'package:connectivity/connectivity.dart';
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
// Connected to a mobile network
} else if (connectivityResult == ConnectivityResult.wifi) {
// Connected to a Wi-Fi network
}
Subscribing to Connectivity Changes:
import 'package:connectivity/connectivity.dart';
@override
initState() {
super.initState();
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Handle connectivity changes
});
}
// Cancel subscription in dispose()
@override
dispose() {
super.dispose();
subscription.cancel();
}
Note: Connectivity changes are no longer communicated to Android apps in the background from Android O onward. Always check for connectivity status when your app resumes to ensure accurate information.
Deprecation Notice
The original connectivity
plugin has been deprecated and replaced by the connectivity_plus
version. Users are encouraged to migrate to the Plus version, which will receive ongoing updates and support.
Example Code
Basic Connectivity Check:
import 'package:connectivity/connectivity.dart';
Future checkConnectivity() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
print("Connected to a mobile network.");
} else if (connectivityResult == ConnectivityResult.wifi) {
print("Connected to a Wi-Fi network.");
} else {
print("No active network connection.");
}
}
Listening for Connectivity Changes:
import 'package:connectivity/connectivity.dart';
StreamSubscription? subscription;
Future listenToConnectivityChanges() async {
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
if (result == ConnectivityResult.none) {
print("Internet connection lost.");
} else {
print("Internet connection restored.");
}
});
}
Note: Provide appropriate handling for connectivity changes to ensure seamless user experiences and prevent potential disruptions.