Flutter Internet Connetion
Mobile Apps Development A-Z Guide.
Give us a message if you’re interested in Blockchain and FinTech software development or just say Hi at Pharos Production Inc.
Or follow us on Youtube to know more about Software Architecture, Distributed Systems, Blockchain, High-load Systems, Microservices, and Enterprise Design Patterns.
The vast majority of mobile applications are very dependent on internet connection. However, if the network is absent under any conditions, then the user should receive information according to the current state of the network. Namely, either the cached data or the message about the disconnection.
In this article, I would like to use a practical example to show how to get information about a connection and how to track it. Material for the article is taken from the official Flutter repository. So, let’s begin!
Step 1. Create a new Flutter project and add to pubspec.yaml next dependency:
dependencies:
connectivity: ^0.4.2
And then you need to run the next command in terminal:
flutter packages get
Step2. Create a ConnectionPage widget:
class ConnectionPage extends StatefulWidget {
ConnectionPage({Key key, this.title}) : super(key: key);
final String title;
@override
_ConnectionPageState createState() => _ConnectionPageState();
}
class _ConnectionPageState extends State<ConnectionPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(),
);
}
Step3. Add the following local variables to the _ConnectionPageState class:
final Connectivity _connectivity = Connectivity();
String _connectionStatus = 'Unknown';
StreamSubscription<ConnectivityResult> _connectivitySubscription
We also display the connection status in the Text widget in the center of the screen:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Text(_connectionStatus),
),
);
}
Step4. We describe a function that will take on the input of a ConnectResult, analyze and save the state accordingly:
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
switch (result) {
case ConnectivityResult.wifi:
String wifiName, wifiIP;
try {
wifiName = (await _connectivity.getWifiName()).toString();
} on PlatformException catch (e) {
print(e.toString());
wifiName = "Failed to get Wifi Name";
}
try {
wifiIP = (await _connectivity.getWifiIP()).toString();
} on PlatformException catch (e) {
print(e.toString());
wifiName = "Failed to get Wifi IP";
}
setState(() {
_connectionStatus = '$result\n'
'Wifi Name: $wifiName\n'
'Wifi IP: $wifiIP\n';
});
break;
case ConnectivityResult.mobile:
case ConnectivityResult.none:
setState(() => _connectionStatus = result.toString());
break;
default:
setState(() => _connectionStatus = 'Failed to get connectivity.');
break;
}
}
Step5. Next, to determine the state of the network at the time of launching the page it’s necessary to use the next function:
Future<void> initConnectivity() async {
ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
print(e.toString());
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return;
}
_updateConnectionStatus(result);
}
Step 6. In order to receive up-to-date information on network status changes, we need to add a listener to the state change event:
@override
void initState() {
super.initState();
initConnectivity();
_connectivitySubscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}
An example of code you can find on the link below:
Thanks for reading.