Retrieving results from Route

When a route is pushed to the navigation, we may want to expect something back from it— for example, when we ask for something from the user in a new route, we can take the value returned via the pop() method's result parameter.

The push method and its variants return a Future. The Future resolves when the route is popped and the value of Future is the pop() method's result parameter.

We have seen that we can pass arguments to a new Route. As the inverse path is also possible, instead of sending a message to the second screen, we can take a message when it pops back.

In Screen 2, we just make sure to return something when doing the pop from Navigator:

// part of navigation_widgetsapp_navigation_result.dart 
class _NavigatorResultAppState
extends State<NavigatorResultApp> {

Widget _screen2(BuildContext context) {
// ... hidden for brevety
RaisedButton(
child: Text("Back to Screen 1"),
onPressed: () {
Navigator.of(context).pop("Good bye from screen 2");
},
),
...
}

The second argument in the pop method is the result from the route.

In the caller screen, we need to take the result back:

// part of navigation_widgetsapp_navigation_result.dart 
class _NavigatorResultAppState
extends State<NavigatorResultApp> {

Widget _screen1(BuildContext context) {
// ... hidden for brevety

RaisedButton(
child: Text("Go to Screen 2"),
onPressed: () async {
final message = await Navigator.of(context).pushNamed('/2') ??
"Came from back button";

setState(() {
_message = message;
});
},
),
...
}
}
Please check out the source code of this chapter on GitHub for the full example.

The result of push is a Future we need to take using the await keyword. Here, we just set it to a new _message variable that is displayed in a text.

If you do not remember how to work with Future, take a look back at Chapter 2, Intermediate Dart Programming, in the Futures and async section.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.247