I'm writing an application which will have two Activities, when the user presses the back button on the second activity a dialog should pop up asking the user to confirm the action. So how do I intercept this? I seriously doubt about this coz the backstack is a part of the OS itself. Has anyone found a workaround?
In simple cases, when you need to intercept the Android back-button, you usually add WillPopScope to your widget tree. However, when developing stateful widgets that interact with the back button, it's more convenient to use the BackButtonInterceptor .
The WillPopScope widget comes with the Flutter framework. It gives us control over the back button action, allowing the current page to go back to the previous one if it meets certain requirements. This is achieved using a callback, which the widget takes in as one of its parameters.
To disable back button in Flutter, you can use the WillPopScope widget. The WillPopScope widget helps you get a callback whenever the back button is pressed. Inside the callback, if you return true the screen will be popped and if you return false, you have simply disabled the back button.
In an activity you can just override
onBackPressed()
edit: that is api lvl 5+ :/ for 4 and below you gotta override onKeyDown()
Simply override the onKeyDown(int, KeyEvent)
method in your activity and look for the back button. Return true
so that the event is consumed.
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //Do something here return true; } return super.onKeyDown(keyCode, event); }
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