Hi coders, in this post, we will learn how to check the internet connection in Flutter.
Sometimes you need to check the internet connection of the device whether online or offline.
Check the device’s connection with mobile data and Wi-Fi if the device is online.
I am going to share a step-by-step tutorial to check the internet connection in your flutter App.
Package Required to Check Internet Connection
Provider – is a wrapper around the InheritedWidget. The provider is one of the best state management officially recommended by the flutter team. The provider consists of three aspects ChangeNotifier, ChangeNotifierProvider, and Consumer. The ChangeNotifier holds the data, ChangeNotifierProvider provides the data, and Consumer uses the data.
Connectivity plus – It is a plugin of flutter that allows flutter apps to discover network connectivity and configure themselves accordingly. This plugin provides every type of connectivity status like mobile data, wifi, Bluetooth, and ethernet. The interesting part of this package is it also notifies real-time status by using StreamSubscription.
Some properties are mentioned below:
Mobile data – ConnectivityResult.mobile
Wifi – ConnectivityResult.wifi
Bluetooth – ConnectivityResult.blutooth
Ethernet – ConnectivityResult.ethernet
You can add these two packages in the dependencies section to your pubsec.yaml file.
1 2 3 4 5 6 7 8 9 |
dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 provider: ^6.0.2 connectivity_plus: ^2.2.1 |
After adding this to your dependencies use the “flutter pub get” command to get this in your dependencies.
Steps to Check Internet Connection in Flutter
Create file check_internet_connectivity.dart
Create class name CheckInternet extends with ChangeNotifier because we are using Provider. The purpose of using provider state management is to avoid setState & easily check an internet connection without rebuilding the UI.
1 2 3 |
class CheckInternet extends ChangeNotifier |
Import connectivity_plus package. To use this package you have to create an instance of the Connectivity class.
1 2 3 4 5 |
import 'package:connectivity_plus/connectivity_plus.dart'; final Connectivity _connectivity = Connectivity(); |
You have to create one more instance of StreamSubscription to notify the real-time changes in the connection state.
1 2 3 |
late StreamSubscription _streamSubscription; |
Create a variable to store the connection status type string. Initially, its status is waiting.
String status = ' waiting...;
Now, create a checkConnectivity function. This function will an asynchronous because we are working over the network. Now create a variable to store connectivity results then check the status by using if/else or you can use switch case, after notifying the change in UI using notifyListner.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import 'dart:async'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/foundation.dart'; class CheckInternet extends ChangeNotifier { String status = 'waiting...'; final Connectivity _connectivity = Connectivity(); late StreamSubscription _streamSubscription; void checkConnectivity() async { var connectionResult = await _connectivity.checkConnectivity(); if (connectionResult == ConnectivityResult.mobile) { status = "Connected to MobileData"; notifyListeners(); } else if (connectionResult == ConnectivityResult.wifi) { status = "Connected to Wifi"; notifyListeners(); } else { status = "Offline"; notifyListeners(); } } |
Check Real-Time Internet Connection
We can check Realtime internet connection with help of Stream. Stream helps to identify Real-time changes in your apps. You must subscribe internet connection status update stream.
The onConnectivityChanged property of the connectivity_plus package detects real-time whatever change in connection.
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 |
void checkRealtimeConnection() { _streamSubscription = _connectivity.onConnectivityChanged.listen((event) { switch (event) { case ConnectivityResult.mobile: { status = "Connected to MobileData"; notifyListeners(); } break; case ConnectivityResult.wifi: { status = "Connected to Wifi"; notifyListeners(); } break; default: { status = 'Offline'; notifyListeners(); } break; } }); } |
Show the Result on Screen
Define the ChangeNotifierProvider in main.dart.
1 2 3 4 5 6 7 |
void main() { runApp( ChangeNotifierProvider(create: (_) => CheckInternet(), child: const MyApp())); } |
Create an instance of CheckInternet class, Where you would want to check the internet connection.
CheckInternet? _checkInternet;
Initialize the provider of _checkInternet in the init function, You need to import the provider package.
1 2 3 4 5 6 7 8 |
@override void initState() { _checkInternet = Provider.of<CheckInternet>(context, listen: false); _checkInternet?.checkRealtimeConnection(); super.initState(); } |
Now we have to create a consumer of CheckInternet that can help to show on screen whatever status we got from CheckInternet class.
The consumer is a part of the provider state management, it helps to show the result on screen whatever change in the state without rebuilding the widget.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Consumer<CheckInternet>(builder: (context, provider, child) { return Container( width: double.maxFinite, height: 40, color: provider.status == "Offline" ? Colors.red : Colors.green, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [Text(provider.status)], ), ); }), |
Results:
Now, you can check the internet connection Entire the app.
So that is all for this post. I hope you enjoyed it and learned something. The full code is available on GitHub. If you think this post was helpful, please share it with your friends. Thank You 🙂