How to check network Connectivity in flutter

How to check network Connectivity in flutter

How to check network Connectivity in flutter – Checking a device’s network Connectivity in flutter status is made simple using the Connectivity Flutter package. Accessing this information lets you know if the gadget is online and, if so, how it’s linked (WiFi or mobile data).

Connectivity in flutter, a class included in the package, has functions for checking and listening for connection changes. Moreover, an enum named ConnectivityResult is provided with values for mobile, wifi, and none to describe the various network connectivity states.

Create Flutter apps that show a notice when the device is offline or disable functionality that need an online connection with the help of the connectivity_plus package.

To use the Connectivity in flutter package, you can follow these steps:

  • Add the connectivity_plus package to your pubspec.yaml file:
dependencies:
  connectivity_plus: ^3.0.3
  • Import the package in your Dart code:
import 'package:connectivity_plus/connectivity_plus.dart';
  • Check the network connection status:
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
  // Connected to internet
} else {
  // Not connected to internet
}
  • Listen to changes in network Connectivity in flutter:
StreamSubscription subscription;

subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
  if (result == ConnectivityResult.mobile || result == ConnectivityResult.wifi) {
    // Connected to internet
  } else {
    // Not connected to internet
  }
});

Note: The Connectivity in flutter package is an updated version of the connectivity package that provides better performance and support for newer versions of Flutter. The usage of both packages is very similar, but the connectivity_plus package is recommended for new projects.

How to use the Connectivity in flutter package example to check network Connectivity in flutter status:

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

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

class FlutterFluxApp extends StatefulWidget {
  @override
  _FlutterFluxAppState createState() => _FlutterFluxAppState();
}

class _FlutterFluxAppState extends State {
  StreamSubscription? _subscription;
  String _connectionStatus = 'Unknown';

  @override
  void initState() {
    super.initState();
    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      setState(() {
        _connectionStatus = _getStatusString(result);
      });
    });
  }

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

  String _getStatusString(ConnectivityResult result) {
    switch (result) {
      case ConnectivityResult.mobile:
        return 'Mobile data';
      case ConnectivityResult.wifi:
        return 'WiFi';
      case ConnectivityResult.none:
        return 'No internet connection';
      default:
        return 'Unknown';
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Connection status:'),
              Text(
                _connectionStatus,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

this example, we use the onConnectivityChanged method of the Connectivity class to listen for changes in network connectivity. The _getStatusString method is used to convert the ConnectivityResult enum values into human-readable strings. When the connectivity changes, we update the _connectionStatus variable and update the UI to display it.

Note that we also cancel the subscription to the Connectivity in flutter stream in the dispose method to avoid memory leaks.

No internet connection Screen

you can display a “no internet connection” screen by following these steps:

  • Create a new widget that represents your “no internet connection” screen. You can use any combination of widgets to create your screen, depending on your design needs.
class NoInternetScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.signal_wifi_off, size: 100),
            SizedBox(height: 16),
            Text('No internet connection',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('Please check your internet connection and try again',
                textAlign: TextAlign.center)
          ],
        ),
      ),
    );
  }
}
  • Use a package like connectivity to check the internet Connectivity in flutter status of the device.
import 'package:connectivity/connectivity_plus.dart';

Future checkInternetConnectivity() async {
  var connectivityResult = await (Connectivity().checkConnectivity());
  return connectivityResult != ConnectivityResult.none;
}
  • In your widget tree, conditionally show your “no internet connection widget” screen based on the connectivity status of the device.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: FutureBuilder(
        future: checkInternetConnectivity(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            // Show a loading spinner while checking connectivity status
            return CircularProgressIndicator();
          } else {
            // Show the "no internet connection" screen if there is no connectivity
            if (snapshot.hasError || !snapshot.data!) {
              return NoInternetScreen();
            }
            // Show the main app screen if there is connectivity
            return MyHomePage();
          }
        },
      ),
    );
  }
}

This code utilizes the Connectivity in flutter package to verify the device’s connectivity status, displays a loading spinner while the check is in progress, and then either displays the “no internet connection” screen or the main app screen depending on the check’s outcome.

full example that demonstrates how to implement a “no internet connection” screen in Flutter:

no internet connection screen in Flutter
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

void main() => runApp(FlutterFluxApp());

class FlutterFluxApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: InternetConnectionWrapper(child: MyHomePage()),
    );
  }
}

class InternetConnectionWrapper extends StatefulWidget {
  final Widget child;

  const InternetConnectionWrapper({required this.child});

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

class _InternetConnectionWrapperState extends State {
  bool _isConnected = true;

  @override
  void initState() {
    super.initState();
    checkInternetConnectivity();
    Connectivity().onConnectivityChanged.listen((result) {
      setState(() {
        _isConnected = result != ConnectivityResult.none;
      });
    });
  }

  Future checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    setState(() {
      _isConnected = connectivityResult != ConnectivityResult.none;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _isConnected ? widget.child : NoInternetScreen();
  }
}

class NoInternetScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.signal_wifi_off, size: 100),
            SizedBox(height: 16),
            Text('No internet connection',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('Please check your internet connection and try again',
                textAlign: TextAlign.center)
          ],
        ),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: Text('Welcome to FlutterFlux!'),
      ),
    );
  }
}

InternetConnectionWrapper widget wraps the MyHomePage widget. InternetConnectionWrapper is responsible for checking the internet Connectivity in flutter status of the device and conditionally showing the “no internet connection” screen or the main app screen.

no internet connection screen in Flutter

The NoInternetScreen widget represents the “no internet connection” screen and displays a message and an icon indicating that the device is not connected to the internet.

The MyHomePage widget represents the main app screen and simply displays a welcome message.

The checkInternetConnectivity() function checks the internet connectivity status of the device using the connectivity package and updates the _isConnected variable accordingly. The _isConnected variable is used to conditionally show the “no internet connection” screen or the main app screen.

The onConnectivityChanged stream is used to listen for changes in the internet connectivity status of the device. Whenever the Connectivity in flutter status changes, the _isConnected variable is updated, and the UI is rebuilt accordingly.

No internet connection dialog in Flutter

How to check network Connectivity in flutter

how to display a “No internet connection” dialog using the Connectivity in flutter package:

import 'dart:isolate';
import 'dart:ui';

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

void main() => runApp(FlutterFluxApp());

class FlutterFluxApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  bool _isConnected = false;
  final Connectivity _connectivity = Connectivity();
  ReceivePort _port = ReceivePort();
  @override
  void initState() {
    super.initState();
    _prepare();

    _bindConnection();
  }

  void _prepare() async {
    ConnectivityResult connectivityResult =
        await _connectivity.checkConnectivity();

    if (connectivityResult == ConnectivityResult.none) {
      _noConnectionModal();

      _isConnected = true;
    }

    _connectivity.onConnectivityChanged.listen((event) {
      if (event == ConnectivityResult.none) {
        _noConnectionModal();

        _isConnected = true;
        return;
      }

      if (_isConnected) {
        Navigator.of(context).pop();

        _isConnected = false;
      }
    });
  }

  Future _noConnectionModal() {
    bool shouldPop = false;

    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => WillPopScope(
        onWillPop: () async => shouldPop,
        child: Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          backgroundColor: Colors.blue,
          child: Padding(
            padding: const EdgeInsets.all(10.0 * 2),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                    padding: const EdgeInsets.all(10.0 * 2),
                    decoration: BoxDecoration(
                      color: Colors.deepPurple,
                      borderRadius: BorderRadius.circular(100.0),
                    ),
                    child: Icon(Icons.wifi_off_outlined)),
                const SizedBox(height: 10.0 * 2),
                const Text(
                  "No internet connection!",
                  style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 20.0,
                  ),
                ),
                const SizedBox(height: 10.0),
                const Text(
                  "Make sure Wi-Fi or mobile data is turned on then try again",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 16.0,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _bindConnection() {
    bool isSuccess =
        IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader');
    if (!isSuccess) {
      _unbindConnection();
      _bindConnection();
      return;
    }
  }

  void _unbindConnection() {
    IsolateNameServer.removePortNameMapping('downloader');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: Center(
        child: Text(
          _isConnected ? 'Internet Connected' : 'No Internet Connection',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
    );
  }
}

The app’s main page, _MyHomePageState, calls the _prepare() function in its initState() method. _noConnectionModal() displays a dialog if the device has no internet connection. Otherwise, the program shows “Check your internet connection” in the middle.

Module ‘connectivity_plus’ not found

An absence of the Connectivity in flutter package will result in the “module ‘connectivity_plus‘ not found” error in a Flutter project.

Following these instructions will allow you to successfully install the package:

  • Open your Flutter project in an editor or IDE.
  • Open the pubspec.yaml file in your project.
  • Under the dependencies section, add the following line:
connectivity_plus: ^3.0.3

This will add the latest version of the connectivity_plus package to your project.

  • Save the changes to the pubspec.yaml file.
  • Run flutter pub get in the terminal to install the package and its dependencies.
  • Once the package is installed, you can import it in your Dart code like this:
import 'package:connectivity_plus/connectivity_plus.dart';
  • You can now use the package in your Flutter project.

If problems persist, you may clear the cached dependencies using flutter clean and give flutter pub get another go. If you’re still having trouble, you may ask for advice from the Flutter community or a professional in the area. Click here to access the project’s code repository.

Conclusion

Flutter connects mobile apps well. It supports many services and platforms via APIs and plugins. Flutter lets developers build apps that connect to the internet, use online services, and share data with other devices. Flutter’s reactive programming and widget-based design make responsive, scalable, cross-platform apps easy to build.

Hello, I'm Cakra. I'm currently occupied with developing an application using the Flutter framework. Additionally, I'm also working on writing some articles related to it.

You May Also Like