Flutter Future<bool> vs bool type
Asked Answered
L

2

32

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;
        });
  }
}
Luminous answered 24/9, 2018 at 10:35 Comment(0)
C
45

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.

Cablegram answered 24/9, 2018 at 11:18 Comment(0)
H
23

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);
    }
  }
Harar answered 31/3, 2020 at 3:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.