1

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

  • What you want to do with `_wifiEnabled`? Show something in UI? – Dinesh Balasubramanian Sep 30 '18 at 07:13
  • Pretty much. If the user doesn't have wifi enabled I'd just show them a dialog box informing to turn on wifi and then exit from the application. Otherwise I'd allow functionality that requires the internet. On reflection I might just try checking for socket exceptions on internet requests if I can't get this way to work. – user4169362 Oct 01 '18 at 07:49

1 Answers1

0

Hope below code helps you to get the idea.

class YourWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    showWifiAlert();
    return ...
  }

  void showWifiAlert() async {
     var wifiEnabled = await getWifiStatus();
     if (wifiEnabled) {
       //Do stuff
     }
   else {
     //Ask user to enable internet
    }
  }

  Future<bool> getWifiStatus() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        print('connected');
       return true;
      }
    } on SocketException catch (_) {
     print('not connected');
     return false;
   }
  }

}
Dinesh Kachhot
  • 385
  • 5
  • 15
Dinesh Balasubramanian
  • 20,532
  • 7
  • 64
  • 57