我的Flutter项目有一个utility.dart文件和一个main.dart文件。我在main.dart文件中调用了函数,但是有问题。它总是显示警告“ 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;
});
}
}
答案 0 :(得分:6)
您需要从bool
中取出Future<bool>
。使用可以then block
或await
。
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");
}
有关更多详细信息,请参见here。
答案 1 :(得分:5)
在Future函数中,您必须返回将来的结果,因此您需要更改以下项的返回值:
return true;
收件人:
return Future<bool>.value(true);
具有正确回报的全部功能是:
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);
}
}