I'm making a Flutter App where I want to check whether or not a user has wifi enabled before proceeding to a different action.
if (wifiEnabled) {
//Do stuff
}
else {
//Tell the user to turn on wifi
}
I have a code snippet that allows me to check whether a user has an internet connection from this post. Check whether there is an Internet connection available on Flutter app
void _checkWifi() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
_wifiEnabled = true;
}
} on SocketException catch (_) {
print('not connected');
_wifiEnabled = false;
}
}
The issue I am having though is that because the checkWifi function is asynchronous. If the user goes from having no wifi to having wifi the boolean isn't updated by the time the if(wifiEnabled) code is checked so according to the logic wifiEnabled will be false, despite the user having wifi.
If the user were to try again however they would have wifi as the wifiEnabled will be updated to true. I've tried using Timer and Future.delayed but I haven't been able to solve my issue so far.
Any advice for dealing with the issue or async calls in general would be very helpful. Thanks