Flutter Back button with return data

Solution 1:

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

Solution 2:

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

Solution 3:

This may help and work for you

1st screen

void goToSecondScreen()async {
 var result = await Navigator.push(_context, new MaterialPageRoute(
 builder: (BuildContext context) => new SecondScreen(context),
 fullscreenDialog: true,)
);

Scaffold.of(_context).showSnackBar(SnackBar(content: Text("$result"),duration: Duration(seconds: 3),));
}

2nd screen

Navigator.pop(context, "Hello world");