3 min read

While developing the Flutter app, you might want to check the internet connection status. Maybe you want to do it before hitting the API call or listening to the internet connection status/stream to let users know about it proactively. So in this tutorial, we’ll see the step-by-step guide the implement Flutter internet connection checker.

Here’s what the final solution looks like:

 Flutter internet connection checker

Here’s what we’ll cover:

How to check internet connection in Flutter

To check the internet connection in Flutter, you need to add the connectivity plus plugin and then you can check the internet connection by manually calling its checkConnectivitymethod or listen to the network connectivity changes by calling its onConnectivityChanged.listen method.

Steps to implement Flutter internet connection checker

Here are the simple steps to implement Flutter internet connection checker:

Step 1: Add the connectivity plus plugin inside the pubspec.yamlfile.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  intl: ^0.17.0
  connectivity_plus: ^2.3.0 # <-- SEE HERE

Step 2: Create a singleton class that is responsible for handling network-related methods.

class NetworkConnectivity {
  NetworkConnectivity._();
  static final _instance = NetworkConnectivity._();
  static NetworkConnectivity get instance => _instance;
  final _networkConnectivity = Connectivity();
  final _controller = StreamController.broadcast();
  Stream get myStream => _controller.stream;
  // 1. 
  void initialise() async {
    ConnectivityResult result = await _networkConnectivity.checkConnectivity();
    _checkStatus(result);
    _networkConnectivity.onConnectivityChanged.listen((result) {
      print(result);
      _checkStatus(result);
    });
  }
// 2.
  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      isOnline = false;
    }
    _controller.sink.add({result: isOnline});
  }
  void disposeStream() => _controller.close();
}
  1. This calls for both methods to manually check the internet connection and listen for the connectivity stream.
  2. After getting connection status, this method ensures that users really have an internet connection by making a network call to example.com.

Step 3: Add Variables that hold the connectivity type and its status.

Map _source = {ConnectivityResult.none: false};
final NetworkConnectivity _networkConnectivity = NetworkConnectivity.instance;
String string = '';

Step 4: Inside the initState method, initialize the network class and listen for the changes.

void initState() {
  super.initState();
  _networkConnectivity.initialise();
  _networkConnectivity.myStream.listen((source) {
    _source = source;
    print('source $_source');
    // 1.
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        string =
            _source.values.toList()[0] ? 'Mobile: Online' : 'Mobile: Offline';
        break;
      case ConnectivityResult.wifi:
        string =
            _source.values.toList()[0] ? 'WiFi: Online' : 'WiFi: Offline';
        break;
      case ConnectivityResult.none:
      default:
        string = 'Offline';
    }
    // 2.
    setState(() {});
    // 3.
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          string,
          style: TextStyle(fontSize: 30),
        ),
      ),
    );
  });
}
  1. This stores the connection type and its status
  2. This refreshes the page to update the connection status text.
  3. This shows the Snackbar with the latest connection status.

Step 5: Build a UI that displays the internet connection.

Center(
    child: Text(
  string,
  style: TextStyle(fontSize: 54),
 ),
)

Step 6: Dispose the stream.

@override
void dispose() {
  _networkConnectivity.disposeStream();
  super.dispose();
}

Here’s the full code:

import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class ConnectionCheckerDemo extends StatefulWidget {
  const ConnectionCheckerDemo({Key? key}) : super(key: key);
  @override
  State<ConnectionCheckerDemo> createState() => _ConnectionCheckerDemoState();
}
class _ConnectionCheckerDemoState extends State<ConnectionCheckerDemo> {
  Map _source = {ConnectivityResult.none: false};
  final NetworkConnectivity _networkConnectivity = NetworkConnectivity.instance;
  String string = '';
  @override
  void initState() {
    super.initState();
    _networkConnectivity.initialise();
    _networkConnectivity.myStream.listen((source) {
      _source = source;
      print('source $_source');
      // 1.
      switch (_source.keys.toList()[0]) {
        case ConnectivityResult.mobile:
          string =
              _source.values.toList()[0] ? 'Mobile: Online' : 'Mobile: Offline';
          break;
        case ConnectivityResult.wifi:
          string =
              _source.values.toList()[0] ? 'WiFi: Online' : 'WiFi: Offline';
          break;
        case ConnectivityResult.none:
        default:
          string = 'Offline';
      }
      // 2.
      setState(() {});
      // 3.
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            string,
            style: TextStyle(fontSize: 30),
          ),
        ),
      );
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        
        backgroundColor: const Color(0xff6ae792),
      ),
      body: Center(
          child: Text(
        string,
        style: TextStyle(fontSize: 54),
      )),
    );
  }
  @override
  void dispose() {
    _networkConnectivity.disposeStream();
    super.dispose();
  }
}
class NetworkConnectivity {
  NetworkConnectivity._();
  static final _instance = NetworkConnectivity._();
  static NetworkConnectivity get instance => _instance;
  final _networkConnectivity = Connectivity();
  final _controller = StreamController.broadcast();
  Stream get myStream => _controller.stream;
  void initialise() async {
    ConnectivityResult result = await _networkConnectivity.checkConnectivity();
    _checkStatus(result);
    _networkConnectivity.onConnectivityChanged.listen((result) {
      print(result);
      _checkStatus(result);
    });
  }
  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      isOnline = false;
    }
    _controller.sink.add({result: isOnline});
  }
  void disposeStream() => _controller.close();
}

Conclusion

In this tutorial, we learned how to implement the Flutter Internet Connection Checker with a practical example. For this tutorial, we used the connectivity plus plugin and used its methods to check the internet connection. We saw both the approach of checking internet connection manually and listening to the connectivity status changes automatically.

Would you like to check other interesting Flutter tutorials?