我正在我的应用程序中处理后退按钮,但我在颤动中遇到了这个问题 非常感谢提前 我以前用这个功能这样做,但现在它不起作用 我认为是因为空安全 对不起,我的英语不好 screenshot
这是我的颤振医生
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1110], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] VS Code (version 1.58.2)
[√] Connected device (3 available)
• No issues found!
这是我的构建方法和 Future 函数
Future<bool> _onBackPress() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('Exit From The App'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPress,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
brightness: Brightness.dark,
title: Text('Internet Availability Checker'),
),
),
);
}
答案 0 :(得分:0)
在您的 _onBackPress()
函数中,您没有返回布尔值。应该这样改写:
Future<bool> _onBackPress() async {
bool goBack = false;
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('Exit From The App'),
actions: [
TextButton(
onPressed: () {
goBack = false;
Navigator.pop(context);
},
child: Text('No'),
),
TextButton(
onPressed: () {
goBack = true;
Navigator.pop(context);
},
child: Text('Yes'),
),
],
);
},
);
return goBack;
}
答案 1 :(得分:0)
showDialog 是一个异步函数,这意味着它会等到某个结果。在这种情况下 - 直到对话框关闭。因为它是异步的,所以您可以在 showDialog 右括号之后添加 .then(意思是“收到值时”)。
<块引用>.then((value) => value ?? false);
顺便说一下,默认情况下“值”为空,当您尝试点击对话框区域外以处理它时,它将为空。为避免返回空值,请使用 '??'检查以将默认值(在 null 的情况下)设置为 false
Future<bool> _onBackPress() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('Exit From The App'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes'),
),
],
);
},
).then((value) => value ?? false);
}