我正在使用Flutter在我的应用程序中创建一个“注册”部分,并尝试执行以下操作:
用户单击“注册”
用户在注册过程中的任何阶段都按下后退按钮
然后弹出一个警告对话框,询问用户是否真的要退出注册过程
用户按下是
然后将用户带回到应用程序的第一(主)页面。
单击注册后此功能适用于第一页,但是当我进入第二页时,步骤4 使我停留在同一页上,然后再次尝试时可以使用。但这不是事实。
经过调试后,我发现了问题,但不知道为什么会发生。
我在onBackPressed()
函数末尾的第二个代码段中以注释的形式编写了该问题,因此很清楚它的中断位置:)。
这是我的代码,用于从我的 main.dart 导航至注册过程页面:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SignUp())
)
然后在注册过程中的每一页上,每当我进入下一页时,都会执行Navigation.pop(context)
以从堆栈中弹出当前注册页,并执行Navigation.push()
之后立即推送下一页。
以下是每个注册页面中后退按钮功能的代码:
bool backIsPressed = false;
Tools _tools = new Tools();
@override
void initState() {
super.initState();
BackButtonInterceptor.add(onBackPressed);
}
@override
void dispose() {
BackButtonInterceptor.remove(onBackPressed);
super.dispose();
}
bool onBackPressed(bool stopDefaultButtonEvent) {
this.backIsPressed = !backIsPressed;
if(backIsPressed) {
_tools.yesNoAlert(
context,
"Going Back?",
"Are you sure you want back? Changes made will not be saved.",
() {
this.backIsPressed = false;
Navigator.pop(context, true);
},
() {
this.backIsPressed = false;
Navigator.pop(context, false);
},
).then((res) {
// ---------------- BREAKS HERE -----------------
// "res" returns null the first time YES is pressed
// But Navigation.pop(context, true) should return true according to Flutter's docs
if(res) {
Navigator.pop(context);
}
});
}
else {
Navigator.pop(context);
}
return true;
}
最后,是yesOrNoAlert()
类中的Tools
函数。
Future<bool> yesNoAlert(BuildContext context, String title,
String description, Function yesFunction, Function noFunction) {
this._isDialogOpen = true;
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(title),
content: new Text(description),
actions: <Widget>[
new FlatButton(
child: new Text('Yes'),
onPressed: () {
_isDialogOpen = false;
yesFunction();
},
),
new FlatButton(
child: new Text('No'),
onPressed: () {
_isDialogOpen = false;
noFunction();
},
)
],
);
});
}
希望我解释得很好。
答案 0 :(得分:1)
如果要返回第一页,而不是pop(),则可以在用户选择yes时使用popUntil()...不需要传递“ res”
在此处详细了解:https://api.flutter.dev/flutter/widgets/Navigator/popUntil.html