My Flutter project has a utility.dart file and a main.dart file. I call the functions in the main.dart file but it has problems. It always showAlert "OK", i think the problem is the the utility class checkConnection() returns a future bool type.
main.dart:
if (Utility.checkConnection()==false) { Utility.showAlert(context, "internet needed"); } else { Utility.showAlert(context, "OK"); }
utility.dart:
import 'package:flutter/material.dart'; import 'package:connectivity/connectivity.dart'; import 'dart:async'; class Utility { static Future<bool> checkConnection() async{ ConnectivityResult connectivityResult = await (new Connectivity().checkConnectivity()); debugPrint(connectivityResult.toString()); if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)){ return true; } else { return false; } } static void showAlert(BuildContext context, String text) { var alert = new AlertDialog( content: Container( child: Row( children: <Widget>[Text(text)], ), ), actions: <Widget>[ new FlatButton( onPressed: () => Navigator.pop(context), child: Text( "OK", style: TextStyle(color: Colors.blue), )) ], ); showDialog( context: context, builder: (_) { return alert; }); } }
You need to get the bool
out of Future<bool>
. Use can then block
or await
.
with then block
_checkConnection() { Utiliy.checkConnection().then((connectionResult) { Utility.showAlert(context, connectionResult ? "OK": "internet needed"); }) }
with await
_checkConnection() async { bool connectionResult = await Utiliy.checkConnection(); Utility.showAlert(context, connectionResult ? "OK": "internet needed"); }
For more details, refer here.
In Future functions you must return future results, so you need to change the return of:
return true;
To:
return Future<bool>.value(true);
So full function with correct return is:
static Future<bool> checkConnection() async{ ConnectivityResult connectivityResult = await (new Connectivity().checkConnectivity()); debugPrint(connectivityResult.toString()); if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)){ return Future<bool>.value(true); } else { return Future<bool>.value(false); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With