Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Future<bool> vs bool type

Tags:

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"); }  

enter image description here

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;         });   } } 
like image 820
GPH Avatar asked Sep 24 '18 10:09

GPH


2 Answers

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.

like image 85
Dinesh Balasubramanian Avatar answered Sep 20 '22 03:09

Dinesh Balasubramanian


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);     }   } 
like image 39
AnasSafi Avatar answered Sep 19 '22 03:09

AnasSafi