Flutter how to execute when clicking back button

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)}
        ),

I am checking for both values null or true because the null value is returned when the user hits the BackButton on android screen (the one in the bottom of the screen). I also believe the null will also be returned with the default BackButton in Flutter so you do not actually need to override the leading property, but I have not checked that myself, so it may be worth checking.


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]. -> from documentation):

@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(
  ...
  ),
 );
}

Hopefully I got your question right and that helps :)!


//if you want to perform  any operation on back button so you can use WillPopScope Widget and managed your code inside onWillpop method 

   
 @override
 Widget build(BuildContext context) {
        return WillPopScope( 

        child:Column()),

        onWillPop: onBackPress);
   }
        
   
// this is onBackPress method
 Future<bool> onBackPress() {
        // your code 
   return Future.value(false);
 }