6

How to Check Internet Connection in Flutter

 2 years ago
source link: https://www.simplifiedcoding.net/check-internet-connection-flutter/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Check Internet Connection in Flutter

July 18, 2022July 16, 2022 by Abhishek Kumar

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.

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.

class CheckInternet extends ChangeNotifier

Import connectivity_plus package. To use this package you have to create an instance of the Connectivity class.

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.

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.

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.

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.

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.

@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.

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:

Check internet connection in flutter result 1Check internet connection in flutter result 2

Check internet connection in flutter result 3

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 🙂

Hi, I am Abhishek Kumar, a Flutter Developer, Problem solver & technical writer. For the past year, I am solving problems and implementing them as Apps using Flutter & Dart.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK