flutter handle no internet connection 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) {
}