How to Execute when Clicking Back Button In Flutter ?

· 2 min read
How to Execute when Clicking Back Button In FlutterHow to Execute when Clicking Back Button In Flutter
How to Execute when Clicking Back Button In Flutter

In this article, we will go through how to execute when clicking Back Button in Flutter?

So let’s get started with the same.

How to Execute when clicking the back button In Flutter?

You can override the default back arrow on the AppBarand then specify the value you would like to return to trigger the change of the state when Navigator. pop is called.

Pseudo-Code

So you need to have something like this in your onPressed callback of your navigation button.

onPressed: ()async{
            var nav = await Navigator.of(context).push(newRoute);
            if(nav==true||nav==null){
              //change the state
            }
          },

and in your newRoute you should have something like this:

new AppBar(
        leading: new IconButton(
          icon: new Icon(Icons.arrow_back),
          onPressed: (){Navigator.pop(context,true)}
        ),

You can listen to the pop with WillPopScope (Creates a widget that registers a callback to veto attempts by the user to dismiss the enclosing [ModalRoute]):

The code snippet will look like the below:

@override
Widget build(BuildContext context) {
 return WillPopScope(
  onWillPop: () {
    print('Backbutton pressed (device or appbar button), do whatever you want.');

    //trigger leaving and use own data
    Navigator.pop(context, false);

    //we need to return a future
    return Future.value(false);
  },
  child: Scaffold(
  ...
  ),
 );
}

Conclusion:

In this article, we have been through How to execute when clicking the back button In Flutter?

Hope you enjoy this article. Drop us your feedback/suggestion.

Need support for Flutter App Development?

Thanks for Reading !!!
Keep Learning !!! Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply