check internet connection flutter code example
Example 1: how to handle the case of no internet connection in flutter
I found that just using the connectivity package was not enough to tell if the internet was available or not. In Android it only checks if there is WIFI or if mobile data is turned on, it does not check for an actual internet connection . During my testing, even with no mobile signal ConnectivityResult.mobile would return true.
With IOS my testing found that the connectivity plugin does correctly detect if there is an internet connection when the phone has no signal, the issue was only with Android.
The solution I found was to use the data_connection_checker package along with the connectivity package. This just makes sure there is an internet connection by making requests to a few reliable addresses, the default timeout for the check is around 10 seconds.
My finished isInternet function looked a bit like this:
Future<bool> isInternet() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
if (await DataConnectionChecker().hasConnection) {
return true;
} else {
return false;
}
} else if (connectivityResult == ConnectivityResult.wifi) {
if (await DataConnectionChecker().hasConnection) {
return true;
} else {
return false;
}
} else {
return false;
}
}
The if (await DataConnectionChecker().hasConnection) part is the same for both mobile and wifi connections and should probably be moved to a separate function. I've not done that here to leave it more readable.
Example 2: flutter check internet connection
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
} else if (connectivityResult == ConnectivityResult.wifi) {
}
Example 3: check if internet connected flutter
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');
}