Home > Software design >  Flutter dart async await not working as expected
Flutter dart async await not working as expected

Time:11-14

I am trying to check the internet connection of the mobile device. I am using below code to check the connectivity.

import 'package:flutter/material.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';

class RedirectPage extends StatelessWidget {
  final int? status;
  
  @override
  Widget build(BuildContext context) {
      bool? isDeviceConnected;
      
      () async {
        print("a");
        print(123);
        isDeviceConnected = await checkConnection();
        print(888);
      };
      
      if (isDeviceConnected != null && isDeviceConnected == false) {
        return AppNetworkConnectivityHome();
      } else{
        return HomePage();      
      }
}
}



print(isDeviceConnected); //giving null for the first time and true or false on the second time.

Future<bool?> checkConnection() async {
  bool a = false;
  a = await InternetConnectionChecker().hasConnection;
  print(a);
  return a;
}

how to force wait for the await function to complete

CodePudding user response:

You'd have to await the method call. You've currently defined it as an anonymous function, so depending on where and how you execute it there will be some differences. But it will work if you instead do something like this:

Future<bool?> myMethod() async {
   return await InternetConnectionChecker().hasConnection;
}

...
print(await myMethod());

CodePudding user response:

You can't call async function in build method, you need to use FutureBuilder like this:

return FutureBuilder<bool>(
        future: checkConnection(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                bool data = snapshot.data ?? true;

                if (!data) {
                    return AppNetworkConnectivityHome();
                } else{
                    return HomePage();      
                }
              }
          }
        },
      )
  • Related