如何解决Flutter - 使用 WillPopScope 和自定义对话框来确认应用程序退出
我已经通过这种方式实现了应用退出确认:
return WillPopScope(
onWillPop: _promptExit,child: Container() /*Remaining window layout*/
_promptExit
函数显示对话框以确认退出:
return showDialog(
context: context,builder: (context) => new AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))),title: new Text(Strings.prompt_exit_title),content: new Text(Strings.prompt_exit_content),actions: <Widget>[
FlatButton(
child: new Text(Strings.no),onPressed: () => Navigator.of(context).pop(false),),SizedBox(height: 16),FlatButton(
child: new Text(Strings.yes),onPressed: () => Navigator.of(context).pop(true),],) ??
false;
它有效,但我想使用自定义对话框而不是标准对话框:https://github.com/marcos930807/awesomeDialogs
它在内部调用 showDialog
,所以我尝试了这种方式:
AwesomeDialog dlg = AwesomeDialog(
context: context,dialogType: DialogType.QUESTION,animType: AnimType.BOTTOMSLIDE,title: Strings.prompt_exit_title,desc: Strings.prompt_exit_content,dismissOnBackKeyPress: false,useRootNavigator: true,btnCancelOnPress: () { Navigator.of(context).pop(false);},btnOkOnPress: () { Navigator.of(context).pop(true);},btnOkText: Strings.yes,btnCancelText: Strings.no
);
return dlg.show() ?? false;
但是我不能以这种方式弹出,我正在黑屏。我该怎么办?
解决方法
showDialog
不会弹出对话框本身。所以你需要使用 Navigator.of(context).pop()
并获取返回值。
awesomeDialogs
包装 pop() 函数本身并对返回值 (awesome_dialog.dart) 不做任何处理
...
pressEvent: () {
dissmiss();
btnOkOnPress?.call();
},...
pressEvent: () {
dissmiss();
btnCancelOnPress?.call();
},...
dissmiss() {
if (!isDissmisedBySystem) Navigator.of(context,rootNavigator:useRootNavigator)?.pop();
}
...
所以需要自己处理返回值,不要再次使用pop():
var result;
AwesomeDialog dlg = AwesomeDialog(
context: context,dialogType: DialogType.QUESTION,animType: AnimType.BOTTOMSLIDE,title: Strings.prompt_exit_title,desc: Strings.prompt_exit_content,dismissOnBackKeyPress: false,useRootNavigator: true,btnCancelOnPress: () {result = false;},btnOkOnPress: () {result = true;},btnOkText: Strings.yes,btnCancelText: Strings.no
);
await dlg.show();
return result;
,
是的,你说得对。所以这就是它的样子:
Future<bool> _promptExit() async {
bool canExit;
AwesomeDialog dlg = AwesomeDialog(
context: context,dismissOnTouchOutside: true,btnCancelOnPress: () => canExit = false,btnOkOnPress: () => canExit = true,btnCancelText: Strings.no
);
await dlg.show();
return Future.value(canExit);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。