Flutter – Return Data from Screen

Interaction with UI is an essential part of any application. During the same, there might raise a need to return data from the screen. This kind of interaction can range from selecting an option to navigating to different routes through the various buttons in the UI. In this article, we will explore the process of returning data from a screen in a Flutter application. 

In Flutter, it can be done using the Navigator.pop() method. We will try this by implementing a simple application. To do so follow the below steps:

  • Add a home screen
  • Add a button to launch the selection screen
  • Display the options
  • Transition to the home screen after option selection
  • Display the selection on the home screen

Let’s build a simple app now:

Create a home screen:

We will need a home screen with a button. The button when tapped should load to an options screen. It can be done like shown below:

Dart



filter_none

edit
close

play_arrow

link
brightness_4
code

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Returning Data'),
      ),
      body: Center(child: SelectionButton()),
    );
  }
}

chevron_right


Adding the launch button and selection screen:

To create a launch button to the launch the selection screen and add the selection screen use the following:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

class SelectionButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _navigateAndDisplaySelection(context);
      },
      child: Text('Launch Option Screen'),
    );
  }
  
  _navigateAndDisplaySelection(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => SelectionScreen()),
    );
  }
}

chevron_right


Displaying the options:

We will have 2 options for the sake of simplicity and have data associate with both of them which when tapped can be returned to the home screen.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

class SelectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Options'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                onPressed: () {
                },
                child: Text('Option 1'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                onPressed: () {
                },
                child: Text('Option 2'),
              ),
            )
          ],
        ),
      ),
    );
  }
}

chevron_right


Adding data to the options:

We will attach a onPressed() callback to both option 1 and option 2 which returns the data associated with each of them as shown below:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

ElevatedButton(
  onPressed: () {
    Navigator.pop(context, 'You choose option 1');
  },
  child: Text('Option 1'),
);
ElevatedButton(
  onPressed: () {
    Navigator.pop(context, 'You choose option 2');
  },
  child: Text('Option 2'),
);

chevron_right


Displaying the selection:

We will use snackbar by using the _navigateAndDisplaySelection() method in SelectionButton:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

_navigateAndDisplaySelection(BuildContext context) async {
  final result = await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SelectionScreen()),
  );
  Scaffold.of(context)
    ..removeCurrentSnackBar()
    ..showSnackBar(SnackBar(content: Text("$result")));
}

chevron_right


Complete Source Code:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

import 'package:flutter/material.dart';
  
void main() {
  runApp(MaterialApp(
    title: 'Returning Data',
    home: HomeScreen(),
  ));
}
  
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksForGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Center(child: SelectionButton()),
    );
  }
}
  
class SelectionButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
      ),
      onPressed: () {
        _navigateAndDisplaySelection(context);
      },
      child: Text('Launch Option Screen'),
    );
  }
  
  _navigateAndDisplaySelection(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => SelectionScreen()),
    );
  
    Scaffold.of(context)
      ..removeCurrentSnackBar()
      ..showSnackBar(SnackBar(content: Text("$result")));
  }
}
  
class SelectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Select Option'),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
                ),
                onPressed: () {
                  Navigator.pop(context, ' You selected the Option 1');
                },
                child: Text('Option 1'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
                ),
                onPressed: () {
                  Navigator.pop(context, 'You selected the Option 2');
                },
                child: Text('Option 2.'),
              ),
            )
          ],
        ),
      ),
    );
  }
}

chevron_right


Output:




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.