How to use back button with return data in Flutter ?

· 5 min read
How to use back button with return data in Flutter
How to use back button with return data in Flutter

Navigation is used to redirect users from one screen to another screen. In this article, we will look into how to use the back button with return data in Flutter.

How to use the back button with return data in Flutter?

You can try the below way:

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

On a 2nd Screen

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

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

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

You can do this with the Navigator.pop() method using the following steps:

  • Define the home screen

The home screen displays a button. When tapped, it launches the selection screen.

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Returning Data Demo'),
      ),
      // Create the SelectionButton widget in the next step.
      body: Center(child: SelectionButton()),
    );
  }
}
  • Add a button that launches the selection screen

Now, create the SelectionButton, which does the following:

  1. Launches the SelectionScreen when it’s tapped.
  2. After that wait for the SelectionScreen to return a result.
    class SelectionButton extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return RaisedButton(
          onPressed: () {
            _navigateAndDisplaySelection(context);
          },
          child: Text('Pick an option, any option!'),
        );
      }
    
      // A method that launches the SelectionScreen and awaits the
      // result from Navigator.pop.
      _navigateAndDisplaySelection(BuildContext context) async {
        // Navigator.push returns a Future that completes after calling
        // Navigator.pop on the Selection Screen.
        final result = await Navigator.push(
          context,
          // Create the SelectionScreen in the next step.
          MaterialPageRoute(builder: (context) => SelectionScreen()),
        );
      }
    }
  1. Show the selection screen with two buttons

Now, build a selection screen that contains two buttons. When a user taps a button, that app closes the selection screen and lets the home screen know which button was tapped.

This step defines the UI. The next step adds code to return data.

class SelectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pick an option'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: RaisedButton(
                onPressed: () {
                  // Pop here with "Yep"...
                },
                child: Text('Yep!'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: RaisedButton(
                onPressed: () {
                  // Pop here with "Nope"
                },
                child: Text('Nope.'),
              ),
            )
          ],
        ),
      ),
    );
  }
}
  • When a button is tapped, close the selection screen

Now, update the onPressed() callback for both of the buttons. 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.

RaisedButton(
  onPressed: () {
    // The Yep button returns "Yep!" as the result.
    Navigator.pop(context, 'Yep!');
  },
  child: Text('Yep!'),
);
  1. Show a snackbar on the home screen with the selection

Now that you’re launching a selection screen and awaiting the result, you’ll want to do something with the information that’s returned.

In this case, show a snackbar displaying the result by using the _navigateAndDisplaySelection() method in SelectionButton:

_navigateAndDisplaySelection(BuildContext context) async {
  final result = await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SelectionScreen()),
  );

  // After the Selection Screen returns a result, hide any previous snackbars
  // and show the new result.
  Scaffold.of(context)
    ..removeCurrentSnackBar()
    ..showSnackBar(SnackBar(content: Text("$result")));
}

Conclusion:

Thanks for being with us !!!

So, in this article, we have seen what is Async/Await/then in Dart/Flutter.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget  GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply