Flutter Check Internet Connectivity

Follow @desiprogrammer_

Table Of Contents

Setup Code


Setup

Add the following dependencies in your pubspec file.

 internet_connection_checker: ^0.0.1+1
 connectivity_plus: ^1.0.4

Code

Checking Internet using internet_connection_checker

Future<bool> getInternetUsingInternetConnectivity() async {
  bool result = await InternetConnectionChecker().hasConnection;
  return result;
}

Checking Internet using connectivity_plus

getConnectivity() async {
  var connectivityResult = await (Connectivity().checkConnectivity());
  if (connectivityResult == ConnectivityResult.mobile) {
    // I am connected to a mobile network.
    print("Mobile Data Connected !");
  } else if (connectivityResult == ConnectivityResult.wifi) {
    // I am connected to a wifi network.
    print("Wifi Connected !");
  } else {
    print("No Internet !");
  }
}

Subscribing to internet connectivity changes connectivity_plus

  var subscription;
  String status = "Offline";

  @override
  void initState() {
    super.initState();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.none) {
        setState(() {
          status = "Offline";
        });
      } else {
        setState(() {
          status = "Online";
        });
      }
    });
  }

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