gpt4 book ai didi

Flutter Future 与 bool 类型

转载 作者:IT王子 更新时间:2023-10-29 06:35:34 27 4
gpt4 key购买 nike

我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com