Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading