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

nin*_*2.0 1 back-button flutter

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

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

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

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

Ale*_*kin 13

默认的后退按钮AppBarBackButton来自 的小部件material.dart。您可以手动创建它并传递您自己的onPressed来执行您想要的操作:

return Scaffold(
  appBar: AppBar(
    leading: BackButton(onPressed: _onBackPressed),
    title: Text('Title'),
  ),
  body: Container(),
);
Run Code Online (Sandbox Code Playgroud)

如果您没有指定leadingin AppBar,那么它会创建一个BackButton具有指定 的处理程序Navigator.maybePop(context)


Fil*_*cks 5

您可以使用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(),
        ),
      ),
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

此帖子的答案代码

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

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

Navigator.of(context).pop() 
Run Code Online (Sandbox Code Playgroud)

Navigator.of(context).pop('upload_files')
Run Code Online (Sandbox Code Playgroud)

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

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


 if(navigationResult == 'upload_files') {
    uploadFiles(); // Perform your custom functionality here.
 }
Run Code Online (Sandbox Code Playgroud)