我的 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");
}
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 block
或 await
.
用 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/