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?
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(),
);
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With