如何在Flutter中拦截AppBar中的后退按钮

时间:2019-03-03 18:03:28

标签: flutter back-button

当页面1从页面2返回时,我正在使用拦截器https://pub.dartlang.org/packages/back_button_interceptor执行一种方法。

如果使用设备后退按钮从第2页返回第1页,则该方法将执行。

但是,如果我使用appBar上的箭头按钮从第2页回到第1页,则无法执行该方法。

后退按钮功能如何默认设置为设备后退按钮?

1 个答案:

答案 0 :(得分:3)

您可以使用WillPopScope在第2页上包围您的支架,将onWillPop设置为false以防止系统弹出页面,然后将自己的后退按钮添加到应用程序栏的前导小部件中并在其中进行弹出。

@override
Widget build(BuildContext context) {
  return new WillPopScope(
    onWillPop: () async => false,
    child: new Scaffold(
      appBar: new AppBar(
        title: new Text("data"),
        leading: new IconButton(
          icon: new Icon(Icons.ac_unit),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
    ),
  );
}

this post的答案代码

编辑:添加到第2页以控制导航

除了上面的代码,您还将在下面的页面2中添加以下代码。更改

Navigator.of(context).pop() 

Navigator.of(context).pop('upload_files')

然后在导航的第1页中,您将等待导航,并使用第2页的弹出窗口返回的结果并运行逻辑

var navigationResult = await Navigator.push(
        context,
        new MaterialPageRoute(
            builder: (context) => Page2()));


 if(navigationResult == 'upload_files') {
    uploadFiles(); // Perform your custom functionality here.
 }