Flutter Future< bool> vs布尔型 [英] Flutter Future<bool> vs bool type
本文介绍了Flutter Future< bool> vs布尔型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的Flutter项目有一个utility.dart文件和一个main.dart文件.我在main.dart文件中调用了函数,但是有问题.它总是显示警告"OK",我认为问题是实用程序类checkConnection()返回了将来的布尔类型.
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:
main.dart:
if (Utility.checkConnection()==false) {
Utility.showAlert(context, "internet needed");
} else {
Utility.showAlert(context, "OK");
}
utility.dart:
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 block
或await
.
You need to get the bool
out of Future<bool>
. Use can then block
or await
.
with then block
with 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");
}
有关更多详细信息,请参见此处.
For more details, refer here.
这篇关于Flutter Future< bool> vs布尔型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文