Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter how to execute function on back pressed

Tags:

flutter

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?

like image 790
Victor Ortiz Avatar asked Jan 15 '20 14:01

Victor Ortiz


Video Answer


2 Answers

You are looking to WillPopScope widget.

Usage :

@override
Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
            onBackPressed(); // Action to perform on back pressed 
            return false;
        }, 
        child: Scaffold(),
    );
}
like image 57
Augustin R Avatar answered Sep 22 '22 23:09

Augustin R


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 :)

like image 20
Abbas Avatar answered Sep 18 '22 23:09

Abbas