fazilSizzlers
fazilSizzlers

Reputation: 325

Flutter dart async await not working as expected

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

Upvotes: 0

Views: 633

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17950

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();      
                }
              }
          }
        },
      )

Upvotes: 1

Robert Sandberg
Robert Sandberg

Reputation: 8635

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());

Upvotes: 2

Related Questions