Check connection in Flutter app.
3 min read
Converting a website into a mobile app can be a swift solution to enhance the user experience for your existing website. However, it comes with a drawback: when there's a loss of internet connection, users may encounter a frustrating error message such as "This site can't be reached." This can give the impression that your app is merely a web browser, essentially displaying a link to your website. This is not an ideal user experience and is not recommended if you want to provide a seamless experience for your app users and visitors.
Fortunately, there are some excellent Flutter packages available that can help you circumvent this issue, allowing you to create a more native-like experience for your app users. These packages can ensure that your app remains functional even when there's no internet connection, enhancing the overall user experience.
To use the internet_connection_checker
package in conjunction with connectivity_plus
in a Flutter app, you can follow these steps. This example assumes you have already set up a Flutter project and have added the required dependencies to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
connectivity_plus: ^2.2.2
internet_connection_checker: ^0.4.0
Now, let's create a Flutter app that checks the internet connection using these packages. In this example, we will create a simple app that displays the current internet connection status.
- Import the necessary packages in your Dart file (e.g.,
main.dart
):
// Import necessary packages
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
- Create a Flutter widget that checks the internet connection status and displays it:
void main() {
// Initialize the Flutter app by running MyApp
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// Create a MaterialApp with the InternetConnectionCheckerExample as the home screen
return const MaterialApp(
home: InternetConnectionCheckerExample(),
);
}
}
class InternetConnectionCheckerExample extends StatefulWidget {
const InternetConnectionCheckerExample({super.key});
@override
State createState() => _InternetConnectionCheckerExampleState();
}
class _InternetConnectionCheckerExampleState
extends State<InternetConnectionCheckerExample> {
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
bool _isConnected = false;
@override
void initState() {
super.initState();
// Start monitoring connectivity changes
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
// Check the initial connection status
_updateConnectionStatus(ConnectivityResult.none);
}
@override
void dispose() {
// Cancel the connectivity subscription when the widget is disposed
_connectivitySubscription.cancel();
super.dispose();
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
// Use InternetConnectionChecker to check if there is an internet connection
final isConnected = await InternetConnectionChecker().hasConnection;
setState(() {
_isConnected = isConnected;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Internet Connection Checker'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_isConnected
? 'Connected to the Internet'
: 'No Internet Connection',
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
// Check the internet connection again when the button is pressed
final isConnected =
await InternetConnectionChecker().hasConnection;
setState(() {
_isConnected = isConnected;
});
},
child: const Text('Check Again'),
),
],
),
),
);
}
}
In this example:
We use the
Connectivity
package to monitor changes in connectivity status.We use the
InternetConnectionChecker
package to check if the device has an internet connection.We update the
_isConnected
state variable based on the connection status.The app displays whether it is connected to the internet or not and provides a button to check the connection status again.
Remember to import the required packages and add the dependencies to your pubspec.yaml
file. This example should help you get started with using internet_connection_checker
in conjunction with connectivity_plus
in a Flutter app.