Building a Flutter App with Seamless Internet Connectivity Handling
Internet connectivity is crucial for most mobile applications in today's always-connected world. But what happens when the connection is lost? A great user experience involves handling connectivity gracefully, notifying users when offline, and resuming functionality when the connection is restored.
In this tutorial, we’ll build a Flutter app that detects internet connectivity in real-time and navigates to a No Internet screen when disconnected. Upon regaining connection, the app will automatically return to the main content.
Prerequisites
Before we dive into coding, ensure you have the following:
- A working Flutter environment.
- Basic knowledge of Flutter widgets and navigation.
- The
connectivity_plus
package installed.
To install, add the following to your pubspec.yaml
file:
dependencies:
connectivity_plus: ^6.1.0
Run flutter pub get
to fetch the package.
Step 1: Setting Up Connectivity Monitoring
First, we need a service to monitor connectivity status. This will utilize the connectivity_plus
package to detect real-time connectivity changes.
Create a new file called connectivity_service.dart
:
import 'package:connectivity_plus/connectivity_plus.dart';
class ConnectivityService {
static final Connectivity _connectivity = Connectivity();
static Stream<List<ConnectivityResult>> get connectivityStream =>
_connectivity.onConnectivityChanged;
static Future<bool> isConnected() async {
final result = await _connectivity.checkConnectivity();
return !result.contains(ConnectivityResult.none);
}
}
Step 2: Designing the Screens
Let’s design two screens: the Home Page, which represents the app’s main content, and the No Internet Screen, which appears when the app is offline.
Home Page
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home Page')),
body: const Center(child: Text('You are connected!')),
);
}
}
No Internet Screen
import 'package:flutter/material.dart';
class NoInternetScreen extends StatelessWidget {
const NoInternetScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('No Internet')),
body: const Center(child: Text('Please check your internet connection.')),
);
}
}
Step 3: Adding Connectivity Listener
We’ll use a StreamBuilder
to listen for connectivity changes and navigate between the screens accordingly.
Connectivity Listener
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'connectivity_service.dart';
class ConnectivityListener extends StatelessWidget {
final Widget child;
const ConnectivityListener({super.key, required this.child});
@override
Widget build(BuildContext context) {
return StreamBuilder<List<ConnectivityResult>>(
stream: ConnectivityService.connectivityStream,
builder: (context, snapshot) {
final isConnected =
!(snapshot.data?.contains(ConnectivityResult.none) ?? true);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!isConnected) {
// Navigate to No Internet Screen if disconnected
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => const NoInternetScreen(),
));
} else {
// Pop No Internet Screen if connected
if (Navigator.canPop(context)) Navigator.pop(context);
}
});
return child;
},
);
}
}
The ConnectivityListener
wraps the app’s main content and listens for changes in connectivity. It navigates to the No Internet Screen when offline and pops it when online.
Step 4: Integrating Everything
Finally, let’s integrate everything into the main app:
import 'package:flutter/material.dart';
import 'connectivity_service.dart';
import 'connectivity_listener.dart';
import 'home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Internet Connectivity Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: const ConnectivityListener(child: HomePage()),
);
}
}
How It Works
- Connectivity Monitoring: The
ConnectivityService
listens for connectivity changes usingconnectivity_plus
. - Screen Navigation: The
ConnectivityListener
wraps the app’s main content and listens for connectivity changes. It:
- Navigate to the No Internet Screen when disconnected.
- Automatically returns to the Home Page when the connection is restored.
- User Feedback: Users are notified of connectivity issues and can see when the app reconnects.
Enhancements and Best Practices
- Avoid Navigation Flickering: If the connection toggles rapidly, it may cause unwanted flickering between screens. To address this, debounce connectivity updates using a
Timer
. - Persist Data Offline: Use packages like
hive
ordrift
to save data locally when offline. - Custom UI for Connectivity States: Instead of navigating to a new screen, consider displaying a banner or snack bar for better UX.
Final Thoughts
Handling internet connectivity in a Flutter app is essential for delivering a smooth user experience. With the power of connectivity_plus
and Flutter’s robust navigation system, we’ve built an app that notifies users of connectivity changes and recovers seamlessly when the internet is restored.
Now, you have a foundational structure for internet connectivity handling that you can adapt to your app’s requirements.
Happy coding!