一尘不染

flutter的未来 vs布尔型

flutter

我的Flutter项目有一个utility.dart文件和一个main.dart文件。我在main.dart文件中调用了函数,但是有问题。它总是showAlert“
OK”,我认为问题是实用程序类checkConnection()返回了将来的布尔类型。

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

阅读 269

收藏
2020-08-13

共1个答案

一尘不染

您需要摆脱bool困境Future<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");
}

有关更多详细信息,请参阅此处

2020-08-13