I want the same onBackPressed
logic of Android in flutter application and I want to close the app when I click on phone back button.
Can any one tell me how to do this when we click on phone back not app back button.
android:
@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
To understand onPressed, we need to use it inside a Flutter app, first. Let’s go step by step. First we should import material and call our main OurApp class using void main runApp method. Our next job involves creating a class named as OurApp that extends StatelessWidget and it should have a build () method. print (‘Remote has been pressed.’);
In Flutter, the rough equivalent to a View is a Widget . Widgets don’t map exactly to Android views, but while you’re getting acquainted with how Flutter works you can think of them as “the way you declare and construct UI”. However, these have a few differences to a View.
You can ask the user to confirm that they want to discard their changes when they tap the back button or back navigation arrow. How can catch the back pressed event in Flutter? You can handle a back pressed event in the Flutter with help of WillPopScope widget.
In Android, a LinearLayout is used to lay your widgets out linearly—either horizontally or vertically. In Flutter, use the Row or Column widgets to achieve the same result. If you notice the two code samples are identical with the exception of the “Row” and “Column” widget.
You can use WillPopScope for that.
It's a class that notifies you when the enclosing ModalRoute
(internally used with the Navigator
) is about to be popped. It even leaves you a choice to whether or not you want the pop to happen.
Just wrap the second screen's Scaffold
in a WillPopScope
.
return WillPopScope(
onWillPop: () async {
// You can do some work here.
// Returning true allows the pop to happen, returning false prevents it.
return true;
},
child: ... // Your Scaffold goes here.
);
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