Flutter Future<bool> 与 bool 类型

标签 flutter future

我的 Flutter 项目有一个 utility.dart 文件和一个 main.dart 文件。我调用了 main.dart 文件中的函数,但它有问题。它总是显示警报“OK”,我认为问题是实用程序类 checkConnection() 返回了 future 的 bool 类型。

主飞镖:

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

最佳答案

您需要获取 bool来自 Future<bool> .使用 jar 头then blockawait .

用 then block

_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 .

关于Flutter Future<bool> 与 bool 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477468/

相关文章:

scala - 在 Scala 中使用 Future 和 Promise 取消

unix - Tokio FramedRead.for_each 无限期调用单个响应

Scala Future mapTo由于缺少ClassTag而无法编译

dart - Flutter NetworkImage 动态高度

java-8 - 是否可以将 Function 传递给 ExecutorService 而不是在 Java 8 中调用?

flutter - 如何在 Flutter Web 中使用 Skia/CanvasKit?

android - Flutterfire 配置无法以任何可能的方式工作

flutter - 什么是 future ,我将如何使用它?

Flutter - 依赖注入(inject)

flutter - 增加 AppBar 前导属性的宽度