Flutter Back button with return data

The easier way is to wrap the body in WillPopScope, in this way it will work with the Back Button on the Top AND the Android Back Button on the Bottom.

Here an example where both back buttons return false:

final return = Navigator.of(context).push(MaterialPageRoute<bool>(
    builder: (BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text("New Page"),
        ),
        body: WillPopScope(
          onWillPop: () async {
             Navigator.pop(context, false);
             return false;
          },
          child: newPageStuff(),
        ),
      );
    },
));

In the other answers they suggested to use:

leading: BackButton(...)

I found that this works on with the Back Button on the Top and not with the Android one.

I include anyway an example:

final return = Navigator.of(context).push(MaterialPageRoute<bool>(
    builder: (BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          leading: BackButton(
            onPressed: () => Navigator.pop(context, false),
          ),
          title: Text("New Page"),
        ),
        body: newPageStuff(),
      );
    },
));

The default BackButton takes over the leading property of your AppBar so all you need to do is to override the leading property with your custom back button, for example:

leading: IconButton(
  icon: Icon(Icons.chevron_left),
  onPressed: () => Navigator.pop(context, false),
),
  

Tags:

Flutter