Flutter Navigator example – Send/Return data to/from new Screen

In this tutorial, we’re gonna build a Flutter App that can navigate to a new Screen and back to Home. In this process, we can also send data to the Screen, then return data back.

More Practice: Flutter SQLite example – CRUD Operations with ListView & sqflite plugin

Flutter App Overview

Fill in the text field Name in the Home Screen:

flutter-navigator-example-navigation-send-data-return-data-new-screen-overview-1

Click on Launch Screen Button, App turns into new Screen together with Name data:

flutter-navigator-example-navigation-send-data-return-data-new-screen-overview-2

In the new Screen, click on Greeting Button, we will navigate back to the Home Screen together with ‘Hello -Name-‘:

flutter-navigator-example-navigation-send-data-return-data-new-screen-overview-3

Navigation

Home Screen to send data

In order to navigate to a new Screen, we use the Navigator.push() method.

The push method requires a Route.
>> We can create our own Route, or use the MaterialPageRoute that transitions to the new screen using a platform-specific animation.

We want to navigate to the NewScreen when a user clicks on RaisedButton. We also pass the name to the NewScreen.
>> In build() method, we implement onPressed callback for the RaisedButton:

We will be get the data returned from NewScreen. This is why we use StatefulWidget that has state for update UI automatically.

New Screen
To receive data from Home Screen

NewScreen class is a StatelessWidget and contains name field.

Because this is just a normal StatelessWidget, we simply require that users creating the Screen pass through a name. Then we have a UI using the given name.

To return data back to Home Screen

We will implement the onPressed callback and use the Navitator.pop() method.

Navigator.pop() accepts an optional second argument called result. It will be returned to the Future in Home Screen.

Home Screen to show returned data

We are launching a NewScreen and awaiting the result. When there is something returned, we get and display the result.
>> Update the _navigateToNewScreen() method in our Home Screen: set the _result variable. Then we show _result with a Text:

Practice

Main

lib/main.dart

Home Screen

lib/home.dart

New Screen

lib/newscreen.dart

Source Code

new_screen_navigator_example

By grokonez | July 12, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*