8

I need to call a function when the user presses the back button in my flutter application, in android with java I could use the following code to achieve it

@Override
public void onBackPressed() {
//some function
}

Is there something similar in flutter?

Victor Ortiz
  • 791
  • 1
  • 12
  • 23
  • 2
    Does this answer your question? [How To Override the “Back” button in Flutter?](https://stackoverflow.com/questions/49356664/how-to-override-the-back-button-in-flutter) – AskNilesh Jan 16 '20 at 05:10

2 Answers2

21

You are looking for WillPopScope widget.

Usage :

@override
Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
            onBackPressed(); // Action to perform on back pressed 
            return false;
        }, 
        child: Scaffold(),
    );
}
Augustin R
  • 7,089
  • 3
  • 26
  • 54
11

EDIT: As pointed out by @Augustin, the following way works in ALL cases when the second screen is popped and NOT JUST ONLY WHEN THE BACK BUTTON IS PRESSED.

In short - You can use .then() on the Navigator.push()

Why? and How?

Home Screen - from the screen you're navigating

Second Screen - to the screen you're navigating

The Navigator on the home screen returns a future that gets 'completed' when the page is popped i.e. when the Navigator.pop() runs on the second screen

So, the .then() method on the Navigator.push() (home screen) will run when your page (second screen) is popped.

Something like this - HOME SCREEN

floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).push(MaterialPageRoute(
            builder: (ctx) => SecondPage()
          )).then(
            (context) {
              isAppleRed();
            }
          );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), 

isAppleRed() - Just to keep things clear :p

bool isAppleRed() {
  print('Yes!');
  return true;
}

Once the back button on the SECOND SCREEN is pressed, the code inside the .then block will run.

Hope that is any sort of help for you :)

Abbas
  • 773
  • 6
  • 16
  • 1
    It will also run when you navigate using some code or using an `AppBar` button. This is not stricly related to android hardware backbutton. – Augustin R Jan 15 '20 at 15:17
  • Thank you for your input. I never knew he was strictly referring to the BACK BUTTON and not just navigating back. I think I had missed down on that back button term. Mentioning that at my answer's beginning. – Abbas Jan 15 '20 at 15:22
  • 1
    iPhones do not have a back press button. So you have to come back to the first screen with something like: ```Navigator.of(context, rootNavigator: true).pop(context);``` Can confirm that your method also works in this case. – Anteino Feb 10 '22 at 20:58