Flutter -  How to Check Internet Connection

In this post, we are going to show you how to check the internet connection in Flutter. You will learn to check whether the device's internet connection is available  or not, You can see the example below:

The first step, We need to add connectivity_plus package in project by adding the following lines in pubspec.yaml file.

 

dependencies:
  flutter:
    sdk: flutter
  connectivity_plus: ^2.2.1

 

Then we need to check the internet connection using code like below

import 'package:connectivity_plus/connectivity_plus.dart';
Future<bool> checkConnectivity() async {
    final ConnectivityResult result = await Connectivity().checkConnectivity();
    if (result == ConnectivityResult.mobile) {
      print('Connected to a mobile network.');
      return true;
    } else if (result == ConnectivityResult.wifi) {
      print('Connected to a Wi-Fi.');
      return true;
    } else {
      print('No connection available.');
      return false;
    }
  }

We can easily check internet connection for both mobile and wifi networks using connectivity_plus package. You can see the above example for checking internet connectivity.

 

Full example :

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Errorgram"),
        ),
        body: Container(
            child: Center(
                child: ElevatedButton(
          child: Text("Check internet connection"),
          onPressed: () async {
            bool isCheckConnectivity = await checkConnectivity();
            if (isCheckConnectivity) {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text("Internet connection available."),
              ));
            } else {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text("No internet connection available"),
              ));
            }
          },
        ))));
  }

  Future<bool> checkConnectivity() async {
    final ConnectivityResult result = await Connectivity().checkConnectivity();
    if (result == ConnectivityResult.mobile) {
      print('Connected to a mobile network.');
      return true;
    } else if (result == ConnectivityResult.wifi) {
      print('Connected to a Wi-Fi.');
      return true;
    } else {
      print('No connection available.');
      return false;
    }
  }
}

I hope it will help You. 

Tags: