How to Show Automatic Internet Connection Offline Message in Flutter

3 min read

To implement an automatic internet connectivity message in your Flutter app, you’ll use the connectivity_plus package. This package allows you to determine the device’s connectivity status and react accordingly. Follow the steps below to add this functionality to your app.

Step 1: Add connectivity_plus to Your pubspec.yaml

First, include the connectivity_plus package in your pubspec.yaml file:

Copy
dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^6.0.3

Step 2: Implement the Connectivity Checker

Below is a complete example of how to create a widget that monitors connectivity status and displays an offline message when there is no internet connection.

Copy
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';

class CheckConnection extends StatefulWidget {
  
  _CheckConnectionState createState() => _CheckConnectionState();
}

class _CheckConnectionState extends State<CheckConnection> {
  StreamSubscription? internetConnection;
  bool isOffline = false;
  //set variable for Connectivity subscription listener

  
  void initState() {
    internetConnection =
        Connectivity().onConnectivityChanged.listen((connectivityResult) {
      if (connectivityResult.contains(ConnectivityResult.none)) {
        //there is no any connection
        setState(() {
          isOffline = true;
        });
      } else if (connectivityResult.contains(ConnectivityResult.mobile) ||
          connectivityResult.contains(ConnectivityResult.wifi)) {
        //connection is from Wifi or Mobile
        setState(() {
          isOffline = false;
        });
      }
    });
    super.initState();
  }

  
  void dispose() {
    super.dispose();
    internetConnection?.cancel();
    //cancel internet connection subscription after you are done
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Check Connection",
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              child: errorMessage(
                "No Internet Connection Available",
                isOffline,
              ),
              //to show internet connection message on isOffline = true.
            ),
            Container(
              margin: const EdgeInsets.all(
                30,
              ),
              width: double.infinity,
              child: const Center(
                child: Text(
                  "Check Connections",
                  style: TextStyle(
                    fontSize: 20,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget errorMessage(
    String text,
    bool show,
  ) {
    //error message widget.
    if (show == true) {
      //if error is true then show error message box
      return Container(
        padding: const EdgeInsets.all(
          10.00,
        ),
        margin: const EdgeInsets.only(
          bottom: 10.00,
        ),
        color: Colors.red,
        child: Row(children: [
          Container(
            margin: const EdgeInsets.only(
              right: 6.00,
            ),
            child: const Icon(
              Icons.info,
              color: Colors.white,
            ),
          ), // icon for error message

          Text(
            text,
            style: const TextStyle(
              color: Colors.white,
            ),
          ),
          //show error message text
        ]),
      );
    } else {
      //if error is false, return empty container.
      return Container();
    }
  }
}

Conclusion

By following the above steps, you can seamlessly integrate an internet connectivity checker into your Flutter app. The connectivity_plus package helps you listen for connectivity changes and update the UI accordingly to inform the user when the device is offline. This enhances the user experience by providing immediate feedback on the network status.

Related Blogs
Adjusting MinSdkVersion in Flutter for Android: 2 Simple Approaches [2023]

Adjusting MinSdkVersion in Flutter for Android: 2 Simple Approaches [2023]

Enhance your Flutter app's compatibility by tweaking the Android minSdkVersion. This comprehensive guide covers easy techniques for projects pre and post Flutter 2.8, guaranteeing optimal functionality.

AndroidFlutterFlutter DevelopmentMin Sdk Version

July 20, 2023

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code! Learn best practices for writing maintainable Dart code in Flutter. Explore examples and essential principles for code quality.

Clean CodeCode Best PracticesCode MaintainabilityCode OrganizationCode Readability

June 02, 2023

All about SOLID Principles in Flutter: Examples and Tips

All about SOLID Principles in Flutter: Examples and Tips

Check out this guide on SOLID principles in Flutter by Mihir Pipermitwala, a software engineer from Surat. Learn with real-world examples!

DartFlutterSolid Principles

April 11, 2023

Top 9 Local Databases for Flutter in 2023: A Comprehensive Comparison

Top 9 Local Databases for Flutter in 2023: A Comprehensive Comparison

Looking for the best local database for your Flutter app? Check out our comprehensive comparison of the top 9 local databases for Flutter in 2023.

CodingFlutterFlutter Local DatabasesLearn To CodeNosql

April 06, 2023

Related Tutorials
A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

A quick guide for you to understand and choose which Button widget suits your needs

FlutterFlutter ButtonFlutter DevelopmentText Button

April 17, 2024

How to Show Automatic Internet Connection Offline Message in Flutter

How to Show Automatic Internet Connection Offline Message in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

Connectivity PlusDependenciesFlutterFlutter DevelopmentFlutter Packages

April 09, 2024

Mastering TabBar and TabBarView Implementation in Flutter: A Comprehensive Guide for 2023

Mastering TabBar and TabBarView Implementation in Flutter: A Comprehensive Guide for 2023

Discover the art of implementing TabBar and TabBarView widgets in Flutter with our comprehensive guide for 2023. Learn step by step how to create captivating user interfaces, customize tab indicators, enable scrollable tabs, change tabs programmatically, and more. Elevate your Flutter app's navigation and user experience with expert insights and practical examples.

CodingDefault Tab ControllerFlutterLearn To CodeTab Controller

July 26, 2023

Enhancing File Manipulation in Flutter: Best Practices and Examples

Enhancing File Manipulation in Flutter: Best Practices and Examples

Master Flutter file manipulation like a pro. Our comprehensive blog provides insights on permission management, directory handling, and practical read-write scenarios. Elevate your app's file management.

CodingFlutterFlutter DevelopmentFlutter File OperationFlutter Path Provider

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

idevisual-studiovisual-studio-codevscodeweb
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

automated-dependency-updatesbundlercomposergithubgo-modules
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

cloudkubecostkubernetesopen-sourceself-hosted
Related Recommended Stories
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

awesomecollectionsgithubpythonpython-framework
Found means fixed - Introducing code scanning autofix, powered by GitHub Copilot and CodeQL

Found means fixed - Introducing code scanning autofix, powered by GitHub Copilot and CodeQL

Now in public beta for GitHub Advanced Security customers, code scanning autofix helps developers remediate more than two-thirds of supported alerts with little or no editing.

code-scanningcodeqlcodinggithubgithub-advanced-security
Awesome Java

Awesome Java

A curated list of awesome frameworks, libraries and software for the Java programming language

awesomebuildcachingclicode-analysis
Awesome iOS

Awesome iOS

A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

analyticsapp-routingapp-storeapple-swiftapple-tv