Flutter - Check Internet Connection Examples

This tutorial gives you examples of how to check the internet connection in Flutter.

Sometimes, you may want to check the internet connection of the device that runs your application. If the application is developed using Flutter, you can read the examples in this tutorial.

Using connectivity_plus Package

There's a package called connectivity_plus from Flutter Community that makes it possible to get the current network state easily. First, add it as a dependency in your pubspec.yaml file.

  dependencies:
    connectivity_plus: ^1.0.6

Then, run flutter pub get to install the package.

To use the package, you need to add the import statement below on the file where you want to use it.

  import 'package:connectivity_plus/connectivity_plus.dart';

Get Curthe rent Connectivity State

To get the current connectivity state, you have to get the instance of Connectivity and call its checkConnectivity method. The constructor of Connectivity already returns a singleton, so you can call it multiple times and it will return the same instance. The checkConnectivity method returns ConnectivityResult enum whose values are:

  • wifi: Device connected via Wi-Fi.
  • mobile: Device connected to cellular network.
  • none: Device not connected to any network.f

Below is a function that checks the current connectivity state.

  ConnectivityResult? _connectivityResult;

  Future<void> _checkConnectivityState() async {
    final ConnectivityResult result = await Connectivity().checkConnectivity();

    if (result == ConnectivityResult.wifi) {
      print('Connected to a Wi-Fi network');
    } else if (result == ConnectivityResult.mobile) {
      print('Connected to a mobile network');
    } else {
      print('Not connected to any network');
    }

    setState(() {
      _connectivityResult = result;
    });
  }

Listen to Connectivity State Changes

The package also provides an easy way to listen for connectivity state change events. To do so, you need to use the Connectivity's onConnectivityChanged property, whose type is Stream). Then, call the Stream's listen method and pass a function to be called when the connectivity state changes. The function has to accept a parameter whose type is ConnectivityResult. Inside the function, you can handle what to do if the connectivity state changes. Make sure that you also cancel the subscription when it's no longer used which can be done inside the dispose method.

  ConnectivityResult? _connectivityResult;
  late StreamSubscription _connectivitySubscription;

  @override
  initState() {
    super.initState();

    _connectivitySubscription = Connectivity().onConnectivityChanged.listen((
        ConnectivityResult result
    ) {
      print('Current connectivity status: $result');
      _connectivityResult = result;
    });
  }

  @override
  dispose() {
    super.dispose();

    _connectivitySubscription.cancel();
  }

Keep in mind that the above method only checks whether the device is connected to a Wi-Fi or mobile network. It doesn't check whether the connected network has access to the Internet.

Using InternetAddress.lookup

In order to check whether the device has internet access, you can try to perform an address lookup. In Flutter, it can be done by using dart:io package. It has InternetAddress.lookup method which can be used to perform an address lookup. So, you need to call the method by passing a valid and accessible host. If the result is not empty and not error, it means the lookup is successful and the device is connected to the Internet.

  bool? _isConnectionSuccessful;

  Future<void> _tryConnection() async {
    try {
      final response = await InternetAddress.lookup('www.woolha2.com');

      setState(() {
        _isConnectionSuccessful = response.isNotEmpty;
      });
    } on SocketException catch (e) {
      setState(() {
        _isConnectionSuccessful = false;
      });
    }
  }

If the device is not connected to the internet, you'll get the following error. You'll also get the same error if the given address is invalid.

  SocketException: Failed host lookup: 'www.woolha.com' (OS Error: No address associated with hostname, errno = 7)

Full Code

  import 'dart:async';
  import 'dart:io';
  
  import 'package:flutter/material.dart';
  import 'package:connectivity_plus/connectivity_plus.dart';
  
  void main() => runApp(MyApp());
  
  class MyApp extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: ConnectivityStatusExample(),
      );
    }
  }
  
  extension ParseToString on ConnectivityResult {
  
    String toValue() {
      return this.toString().split('.').last;
    }
  }
  
  class ConnectivityStatusExample extends StatefulWidget {
  
    @override
    State<StatefulWidget> createState() {
      return _ConnectivityStatusExampleState();
    }
  }
  
  class _ConnectivityStatusExampleState extends State<ConnectivityStatusExample> {
  
    static const TextStyle textStyle = const TextStyle(
      fontSize: 16,
    );
  
    ConnectivityResult? _connectivityResult;
    late StreamSubscription _connectivitySubscription;
    bool? _isConnectionSuccessful;
  
    @override
    initState() {
      super.initState();
  
      _connectivitySubscription = Connectivity().onConnectivityChanged.listen((
          ConnectivityResult result
      ) {
        print('Current connectivity status: $result');
        setState(() {
          _connectivityResult = result;
        });
      });
    }
  
    @override
    dispose() {
      super.dispose();
  
      _connectivitySubscription.cancel();
    }
  
    Future<void> _checkConnectivityState() async {
      final ConnectivityResult result = await Connectivity().checkConnectivity();
  
      if (result == ConnectivityResult.wifi) {
        print('Connected to a Wi-Fi network');
      } else if (result == ConnectivityResult.mobile) {
        print('Connected to a mobile network');
      } else {
        print('Not connected to any network');
      }
  
      setState(() {
        _connectivityResult = result;
      });
    }
  
    Future<void> _tryConnection() async {
      try {
        final response = await InternetAddress.lookup('www.woolha.com');
  
        setState(() {
          _isConnectionSuccessful = response.isNotEmpty;
        });
      } on SocketException catch (e) {
        print(e);
        setState(() {
          _isConnectionSuccessful = false;
        });
      }
    }
  
    @override
    Widget build(BuildContext context) {
      return new Scaffold(
        appBar: AppBar(
          title: const Text('Woolha.com Flutter Tutorial'),
          backgroundColor: Colors.teal,
        ),
        body: SizedBox(
          width: double.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Connection status: ${_connectivityResult?.toValue()}',
                style: textStyle,
              ),
              Text(
                'Is connection success: $_isConnectionSuccessful',
                style: textStyle,
              ),
              OutlinedButton(
                child: const Text('Check internet connection'),
                onPressed: () => _checkConnectivityState(),
              ),
              OutlinedButton(
                child: const Text('Try connection'),
                onPressed: () => _tryConnection(),
              ),
            ],
          ),
        ),
      );
    }
  }

Summary

That's how to check the internet connection of a device using Flutter. To check whether the device is connected to a Wi-Fi or mobile network, you can use the connectivity_plus package, which has the capability to check the current connectivity state and listen to connectivity state change. If you want to check whether the device has internet access, you can perform an address lookup.