我的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");
}
Run Code Online (Sandbox Code Playgroud)
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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
Din*_*ian 13
您需要摆脱bool困境Future<bool>。使用可以then block或await。
然后阻止
_checkConnection() {
Utiliy.checkConnection().then((connectionResult) {
Utility.showAlert(context, connectionResult ? "OK": "internet needed");
})
}
Run Code Online (Sandbox Code Playgroud)
等待着
_checkConnection() async {
bool connectionResult = await Utiliy.checkConnection();
Utility.showAlert(context, connectionResult ? "OK": "internet needed");
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此处。
Ana*_*afi 12
在 Future 函数中,您必须返回未来的结果,因此您需要更改以下返回值:
return true;
Run Code Online (Sandbox Code Playgroud)
到:
return Future<bool>.value(true);
Run Code Online (Sandbox Code Playgroud)
所以正确返回的完整功能是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6502 次 |
| 最近记录: |