Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Back button with return data

I have an interface with two buttons that pop and return true or false, like so:

onPressed: () => Navigator.pop(context, false) 

I need to adapt the back button in the appbar, so it pops and also returns false. Is there a way to accomplish this?

like image 488
aksn Avatar asked Aug 20 '18 09:08

aksn


People also ask

How do you return data on flutter?

To return data to the first screen, use the Navigator. pop() method, which accepts an optional second argument called result . Any result is returned to the Future in the SelectionButton.

How do you pass data when popping in flutter?

Flutter: Passing Data when Popping Views in Flutter You can replace the code in _MyHomePageState with these: The main magic is in moveToSecondPage where it is an async function, awaiting for the SecondPage to come back with some “data”, which we assign it to information here.


Video Answer


2 Answers

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(),       );     }, )); 
like image 78
Apoleo Avatar answered Sep 21 '22 08:09

Apoleo


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), ),    
like image 35
Shady Aziza Avatar answered Sep 18 '22 08:09

Shady Aziza