Flutter Future<bool> vs bool 类型

Flutter Future<bool> vs bool type

我的 Flutter 项目有一个 utility.dart 文件和一个 main.dart 文件。我调用了 main.dart 文件中的函数,但它有问题。它总是显示警报 "OK",我认为问题是实用程序 class checkConnection() returns 未来的布尔类型。

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

您需要从 Future<bool> 中获取 bool。使用可以 then blockawait.

然后块

_checkConnection() {
  Utiliy.checkConnection().then((connectionResult) {
    Utility.showAlert(context, connectionResult ? "OK": "internet needed");
  })
}

等待

_checkConnection() async {
 bool connectionResult = await Utiliy.checkConnection();
 Utility.showAlert(context, connectionResult ? "OK": "internet needed");
}

详情请参考here

在 Future 函数中,您必须 return 未来的结果,因此您需要更改 return 的:

return true;

收件人:

return Future<bool>.value(true);

因此 return 的完整函数是:

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