我有以下流程屏幕1->屏幕2->对话框(在单独的小部件中)。
屏幕2显示一个对话框(关闭?是或否)。如果有人按“是”,我想返回到屏幕1,如果他们按“否”,只需关闭对话框并返回到屏幕2。我当前要做的是,当点击“是”时,我将进行两次Navigator.pop(context)。这是一个好习惯吗?有没有办法将屏幕2的上下文传递给我的对话框小部件,这样我就可以直接弹出该小窗口了?
答案 0 :(得分:2)
我个人认为,最好将对话框中的响应传递回页面,然后让页面处理其余部分。
您可以这样做:
//I'm using a raised button just to call the alert as an example...
RaisedButton(
child: Text('Press me'),
//This part here is the important part
onPressed: () async {
//You can return anything when you use Navigator.pop
//In this case I'm returning a bool indicating if the page should close or not.
//You have to await this because it depends on user input.
bool shouldPopResult = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
//The content of your dialog
actions: <Widget>[
// The value you pass here in Navigator.of(context).pop
// is the value that will be stored in shouldPopResult,
// so if "Yes" is pressed, true will return...
// and if "No", false is returned.
FlatButton(
child: Text('Yes'),
onPressed: () => Navigator.of(context).pop(true),
),
FlatButton(
child: Text('No'),
onPressed: () => Navigator.of(context).pop(false),
)
],
),
);
// This is for if the user dismisses the dialog without pressing a button
// In that case shouldPopResult would be null, so I'm setting it to false.
// You can prevent the user from dismissing the dialog
// setting barrierDismissible to false in the showDialog method.
if (shouldPopResult == null) shouldPopResult = false;
// And finally with the dialog already dismissed, you can decide
// to go back or not.
if (shouldPopResult) Navigator.of(context).pop();
});
通常,您可以将对话框提取为小部件,也可以提取用于完全处理对话框响应的函数或其他任何函数。
您可以在Flutter文档here中看到从页面返回数据的示例。