Home > Net >  How to override the back button behaviour in Flutter?
How to override the back button behaviour in Flutter?

Time:05-23

I have a provider that I want to reset upon using the back button to go to the previous screen, so I would like to manually edit the code of the back button's Navigator. Where is this code located?

One solution would be to add a back button in the app bar, but the Android back button will still do its own process and I will miss the code necessary.

CodePudding user response:

You can handle back button navigation by using WillPopScope widget.

In this widget you can handle it in onWillPop method.

Example

@override
 Widget build(BuildContext context) {
        return new WillPopScope(
          child: new Scaffold(
            appBar: new AppBar(
              title: new Text('Page 2'),
            ),
            body: new Center(
              child: new Text('PAGE 2'),
            ),
          ),
          onWillPop: () async {
            return false;
          },
        );
      }

CodePudding user response:

Just found this, worked for me: https://flutteragency.com/how-to-execute-when-clicking-back-button-in-flutter/

  1. Wrap the Scaffold widget with a WillPopScope widget and let Scaffold be its child.

  2. Give the onWillPop property to WillPopScope and make sure you do two things:

Navigator.pop(context, false);
return Future.value(false);

The return is important, the other pop you can edit or do whatever you need before this return statement.

  • Related