Updated 12 February 2024
Internet is a global network that connects billions of computers across the world with each other and to the World Wide Web. Many application need to check Internet Connection before going to proceeds into main screen, So we will check internet connectivity status in flutter.
Internet require to exchange information such as watching tutorials, downloading and uploading content etc. There is a package that allows us to discover the network connectivity status, named connectivity_plus
package.
You can visit our Flutter app development page for more flutter-related information.
First Create a new flutter project and then add following dependency package in pubspec.yaml file.
1 |
connectivity_plus: ^3.0.3 |
Create a new Stateful (ConnectivityPage) Widget, call from main.dart and import the packages.
1 2 3 4 5 |
import 'dart:async'; import 'dart:developer' as developer; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; |
developer :- This library helps to print the logs in console.
services :- It provides the inbuilt classes for handling PlatformException.
After Importing library and packages add the following code inside ConnectivityPage class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
class ConnectivityPage extends StatefulWidget { const ConnectivityPage({Key? key}) : super(key: key); @override State<ConnectivityPage> createState() => _ConnectivityPageState(); } class _ConnectivityPageState extends State<ConnectivityPage> { Connectivity connectivity = Connectivity(); IconData? icon; String connectionType = "No internet connection"; bool isOffline = true; late StreamSubscription<ConnectivityResult> connectionSubscription; @override void initState() { super.initState(); getConnectivity(); connectionSubscription = connectivity.onConnectivityChanged.listen(updateConnectionStatus); } @override void dispose() { connectionSubscription.cancel(); super.dispose(); } Future<void> getConnectivity() async { late ConnectivityResult result; try { result = await connectivity.checkConnectivity(); getConnectionType(result); } on PlatformException catch (e) { developer.log('Couldn\'t check connectivity status', error: e); icon = Icons.signal_wifi_connected_no_internet_4; return; } if (!mounted) { return Future.value(null); } return updateConnectionStatus(result); } Future<void> updateConnectionStatus(ConnectivityResult result) async { getConnectionType(result); if(result == ConnectivityResult.none){ setState(() { isOffline = true; }); } else{ setState(() { isOffline = false; }); } } |
connectivity :- To check connectivity status and connectivity type.
connectionSubscription :- helps to subscribe the internet connection status update stream that helps to show connectivity status automatically when it is changed.
dispose() :- dispose method cancel the subscription when the the widget is remove from the widget tree permanently.
getConnectivity() :- asynchronous method called from initState to check internet connectivity status. Try and catch block use to handle the Exception, If failed to get connection status.
updateConnectionStatus() :- asynchronous method called when connectivity changed.
Create the Build method to create the user interface and display connection status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Internet Connectivity'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(icon, size: 80, color: isOffline ? Colors.red : Colors.green,), Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Text(connectionType, style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),), ), Text("isOffline $isOffline", style: TextStyle(fontSize: 16, fontWeight: FontWeight.normal)) ], ), ), ); } void getConnectionType(result) { if(result == ConnectivityResult.mobile) { connectionType = "Internet connection is from Mobile data"; icon = Icons.network_cell; }else if(result == ConnectivityResult.wifi) { connectionType = "Internet connection is from wifi"; icon = Icons.network_wifi_sharp; }else if(result == ConnectivityResult.ethernet){ connectionType = "Internet connection is from wired cable"; icon = Icons.settings_ethernet; }else if(result == ConnectivityResult.bluetooth){ connectionType = "Internet connection is from Bluetooth tethering"; icon = Icons.network_wifi_sharp; }else if(result == ConnectivityResult.none){ connectionType = "No internet connection"; icon = Icons.signal_wifi_connected_no_internet_4; } } } |
getConnectionType() :- This Method updates the text and icon whenever updateConnectionStatus() method called.
Thanks for reading this article ❤️
I hope this blog will help you to learn about how to check internet connection in flutter and you will be able to implement it. For more updates, make sure to keep following Mobikul Blogs to learn more about mobile app development.
Happy Learning ✍️
You can also check Internet connectivity in swift.
https://www.fluttercampus.com/guide/282/check-internet-connection-flutter/
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
}
class _ConnectivityPageState extends State {
Connectivity connectivity = Connectivity();
IconData? icon;
String connectionType = “No internet connection”;
bool isOffline = true;
late StreamSubscription connectionSubscription;
@override
void initState() {
super.initState();
getConnectivity();
connectionSubscription = connectivity.onConnectivityChanged
.listen((List connectivityResultList) {
if (connectivityResultList.isNotEmpty) {
ConnectivityResult result = connectivityResultList[0];
updateConnectionStatus(result);
}
});
}
Future getConnectivity() async {
late ConnectivityResult result;
try {
List connectivityResult =
await connectivity.checkConnectivity();
if (connectivityResult.isNotEmpty) {
result = connectivityResult[0];
}
getConnectionType(result);
} on PlatformException catch (e) {
developer.log(“Couldn\’t check connectivity status”, error: e);
icon = Icons.signal_wifi_connected_no_internet_4;
return;
}
if (!mounted) {
return Future.value(null);
}
return updateConnectionStatus(result);
}
Future updateConnectionStatus(ConnectivityResult result) async {
getConnectionType(result);
if (result == ConnectivityResult.none) {
setState(() {
isOffline = true;
});
} else {
setState(() {
isOffline = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(“Internet Connectivity”),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 80, color: isOffline ? Colors.red : Colors.green),
Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text(connectionType,
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500)),
),
Text(“isOffline $isOffline”,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.normal)),
],
),
),
);
}
void getConnectionType(result) {
if (result == ConnectivityResult.mobile) {
connectionType = “Internet connection is from Mobile data”;
icon = Icons.network_cell;
} else if (result == ConnectivityResult.wifi) {
connectionType = “Internet connection is from wifi”;
icon = Icons.network_wifi_sharp;
} else if (result == ConnectivityResult.ethernet) {
connectionType = “Internet connection is from wired cable”;
icon = Icons.settings_ethernet;
} else if (result == ConnectivityResult.bluetooth) {
connectionType = “Internet connection is from Bluetooth tethering”;
icon = Icons.network_wifi_sharp;
} else if (result == ConnectivityResult.none) {
connectionType = “No internet connection”;
icon = Icons.signal_wifi_connected_no_internet_4;
}
}
}