简体   繁体   中英

How to intercept back button in AppBar in flutter

I am using interceptor https://pub.dartlang.org/packages/back_button_interceptor to execute a method when the page 1 is back from page 2.

If I come back from page 2 to page 1 using device back button, the method is executed.

But if I come back from page 2 to page 1 using the arrow button at appBar I am not able to execute the method.

How can the back arrow button functionality default to the device back button?

You can surround your scaffold on Page 2 with WillPopScope, set onWillPop to false to prevent the page from being popped by the system and then add your own back button into the app bar's leading widget and perform your pop in there.

@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(),
        ),
      ),
    ),
  );
}

code for the answer from this post

Edit: Addition to Page 2 to control navigation

In addition to the above code you'll add the below code to page 2. Change

Navigator.of(context).pop() 

to

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

Then in your page 1 where you navigate you'll await the navigation and use the result returned from the pop on page 2 and run your logic

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


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

The default back button in AppBar is BackButton widget from material.dart . You may create it manually and pass your own onPressed to do what you want:

return Scaffold(
  appBar: AppBar(
    leading: BackButton(onPressed: _onBackPressed),
    title: Text('Title'),
  ),
  body: Container(),
);

If you do not specify leading in AppBar , then it creates a BackButton with the handler that does Navigator.maybePop(context) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM