How to Monitor Internet Connection Continuously in Flutter: A Step-by-Step Guide
Have you ever shipped an app to discover that something is weirdly behaving because there is no internet? It can be a failed API call, unsynced data, or even a nonloaded image. Whatever the case might be, poor internet actually does ruin the user experience. In this tutorial, we will learn how to always monitor the availability of internet connectivity in Flutter using two of its power packages: connectivity_plus
and internet_connection_checker.
We’ll break everything step by step, and will completely focus on the connectivity logic. By the end of this tutorial, you’ll have a solid solution that you can use to manage availability of internet seamlessly in your Flutter app.
| Why is Consistently Checking Internet Connection Important?
- Enhancing User Experience: Apps that gracefully handle network outages — by showing appropriate messages or fallbacks — are loved by users.
- Preventing Data Loss: Imagine uploading a file or sending a message without realizing you’re offline. Consistent checks can prevent such mishaps.
- Seamless Offline Support: Some apps, like Google Docs, offer offline functionality. You can conditionally save data locally when the user is offline and sync when back online.
- Debugging Easier: Developers can identify and handle network-related issues proactively by knowing the app’s connectivity state.
| Flutter and Internet Connectivity 🖥️
Flutter, by itself, doesn’t provide built-in tools to check internet connectivity. This is where third-party packages like connectivity_plus
and internet_connection_checker
come in handy. Let’s understand their roles:
What is connectivity_plus
?
This package detects the type of network connection the device is using:
- Wi-Fi
- Mobile data
- No network
However, connectivity_plus
does not check actual internet access. For example, you may be connected to a Wi-Fi network without active internet. That’s where the second package shines.
What is internet_connection_checker
?
This package goes one step further by verifying actual internet access.
For instance, if you’re connected to a router but there’s no internet (due to ISP issues), internet_connection_checker
will identify this.
By combining these two packages, you can monitor both connection status and internet availability consistently.
How Using Both Packages Reduces Your Workload
By using these packages together:
- You get real-time connectivity updates with
connectivity_plus
. - You can verify if there’s internet access with
internet_connection_checker
. - You don’t have to write boilerplate code for handling network checks.
- It makes your app more reliable with minimal effort!
Let’s Build It! 🏗️
Here’s how you can consistently monitor internet connectivity in Flutter.
Step 1: Add Dependencies
In your pubspec.yaml
file, add the following:
dependencies:
connectivity_plus: ^2.4.9
internet_connection_checker: ^1.0.0+1
Run the command:
flutter pub get
Step 2: Set Up the Stateful Widget
Create a new widget called InternetCheckScreen
to monitor connectivity dynamically:
class InternetCheckScreen extends StatefulWidget {
const InternetCheckScreen({super.key});
@override
State<InternetCheckScreen> createState() => _InternetCheckScreenState();
}
Step 3: Monitor Connectivity and Internet Access
1. Listen to Connectivity Changes
Subscribe to connection type updates using Connectivity().onConnectivityChanged
.
2. Check Internet Access
Use InternetConnectionChecker()
to verify if the connection is active.
Add the following logic in initState
:
StreamSubscription<List<ConnectivityResult>>? subscription;
bool isInternetConnected = true;
@override
void initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((List<ConnectivityResult> result) async {
bool isConnected = await InternetConnectionChecker().hasConnection;
setState(() {
isInternetConnected = isConnected;
});
});
}
Step 4: Update the UI Dynamically
We’ll show an icon and a message to indicate the connectivity status:
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: isInternetConnected ? Colors.green[50] : Colors.red[50],
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
isInternetConnected ? Icons.wifi : Icons.signal_wifi_off,
size: 100,
color: isInternetConnected ? Colors.green : Colors.red,
),
SizedBox(height: 20),
Text(
isInternetConnected
? "You're online!"
: "No internet connection",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: isInternetConnected ? Colors.green : Colors.red,
),
),
],
),
),
);
}
Step 5: Add Animations (Optional)
To make it visually appealing, we can scale the icon:
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = Tween<double>(begin: 0.75, end: 1.0).animate(CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
));
}
Wrap the icon in a ScaleTransition
:
ScaleTransition(
scale: _animation,
child: Icon(
isInternetConnected ? Icons.wifi : Icons.signal_wifi_off,
size: 100,
color: isInternetConnected ? Colors.green : Colors.red,
),
),
Step 6: Clean Up Resources
Dispose of the subscription and animation controller in the dispose
method:
@override
void dispose() {
_controller.dispose();
subscription?.cancel();
super.dispose();
}
| The Complete Code
Here’s how everything comes together:
Let’s see the result: —
| Conclusion
Congratulations! Now, that you have really got a robust solution to monitor and display internet connectivity in Flutter. You have combined connectivity_plus
with internet_connection_checker
, thereby having created an aspect that improves the experience of the user but reduces the boilerplate in your app code as well.
This will assure your application is graciously handling network failures while clearly and transparently communicating this back to the user and not throwing errors. Now go implement this in your next project — you’ll thank yourself later!
| 🌟 Enjoyed this tutorial?
For more tips, tutorials, and insights into Flutter, be sure to follow my Medium blog! Stay connected, and let’s continue building amazing things together.
This is just Part 47: Ping me on other platforms… too….
👉 Follow me:
- Medium:- Hemant Kumar Prajapati 🧐
- Github💻:- Hemantpra389 🧐
- LinkedIn :- Hemant Prajapati 🧐
Happy coding! 🎉 !! Happy Flutter !!
💬 Comment Section is Open!
Share your thoughts or ask questions below.
👏 Applaud if you enjoyed this!
Your claps help others find this content.
➕ Follow for more!
Stay updated with more tips and tutorials.
🌿 Thank you for reading! If you liked this post and want to support me, you can buy me a coffee here 👇