Check whether there is an Internet connection available on Flutter app

Rissmon Suresh picture Rissmon Suresh · Apr 4, 2018 · Viewed 93.5k times · Source

I have a network call to be executed. But before doing that I need to check whether the device have internet connectivity.

This is what i have done so far:

  var connectivityResult = new Connectivity().checkConnectivity();// User defined class
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {*/
    this.getData();
    } else {
      neverSatisfied();
    }

Above method is not working.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 4, 2018

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

You can use

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}