Network connectivity checker implementation in Flutter

Before proceeding with actions that are totally reliant on the Network, it is crucial to check and show the user whether they have a Network or not. In this article, we will look at how to implement Network Connectivity Checker in Flutter.

About connectivity_plus :

Flutter apps can use this plugin to check network connectivity. It can distinguish between a cellular and a WiFi connection.

Check current Network status:

In Order to get access to all API methods, we need to create the singleton object for Connectivity

final Connectivity _connectivity = Connectivity();

We can get the network status by using the checkConnectivity() method. It may return one of four different network statuses.

  1. Wifi: Device connected via Wi-Fi
  2. Mobile: Device connected to cellular network
  3. Ethernet : Device connected to ethernet network
  4. None: Device not connected to any network
ConnectivityResult connectivityResult = await _connectivity.checkConnectivity();

if (connectivityResult == ConnectivityResult.mobile) {
  // Device connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
  //  Device connected to a wifi network.
}

Receive Updates on Network Changes:

In most instances, we require real-time network updates in order to enable or disable specific elements of the app that are dependent on network connectivity.

  late StreamSubscription < ConnectivityResult > _connectivitySubscription;

 @override
  void initState() {
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_UpdateConnectionState);
    super.initState();
  }

    @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

onConnectivityChanged method used to register the listener and which returns a <StreamConnectivityResult>

 Future< void > _UpdateConnectionState(ConnectivityResult result) async {
    // connectivity status 
  }

The connectivity status will be updated by the listener.

Implementation of Network connectivity checker:

Project setup:

1. Create a new flutter project in your favorite IDE, and remove the boilerplate code. Ref link

2. Add theconnectivity_plus dependency in pubspec.yaml file, and install it by running pub get.

dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^2.0.2

3. Add the following code into the main.dart file

//Flutterant Network connectivity checker 
import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}
//Flutterant Network connectivity checker 
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription< ConnectivityResult > _connectivitySubscription;

  @override
  void initState() {
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_UpdateConnectionState);
    super.initState();
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Network Status"),
        ),
        body: const Center(child: Text("FlutterAnt.com")));
  }

  Future< void > initConnectivity() async {
    late ConnectivityResult result;
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print("Error Occurred: ${e.toString()} ");
      return;
    }
    if (!mounted) {
      return Future.value(null);
    }
    return _UpdateConnectionState(result);
  }

  Future<void> _UpdateConnectionState(ConnectivityResult result) async {
    if (result == ConnectivityResult.mobile ||
        result == ConnectivityResult.wifi) {
      showStatus(result, true);
    } else {
      showStatus(result, false);
    }
  }

  void showStatus(ConnectivityResult result, bool status) {
    final snackBar = SnackBar(
        content:
            Text("${status ? 'ONLINE\n' : 'OFFLINE\n'}${result.toString()} "),
        backgroundColor: status ? Colors.green : Colors.red);
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
}
//Flutterant Network connectivity checker 

4.  Implementation part has been done, let’s run the application and see the output

Output Video:

Thanks for Reading .. 🙂

Leave a Comment