Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the equivalent method of onbackpressed in flutter

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
}
like image 690
kartheeki j Avatar asked Jan 22 '19 12:01

kartheeki j


People also ask

How to use onpressed in flutter?

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.’);

What is the flutter equivalent of a view?

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.

How do you ask a user to discard changes in flutter?

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.

How do I use linearlayout in flutter?

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.


1 Answers

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.
);
like image 79
Marcel Avatar answered Oct 12 '22 13:10

Marcel