Search code examples
flutterback-button

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?


Solution

  • 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.
     }