Return Data from Screen

Create Free Backend With Appwrite

Introduction

In the previous section, you learned how to send data to another screen. Now, you will learn how to return data from the new screen to the previous screen.

Example 1: Pizza Selection

In this example, you will learn to select a pizza from a list of pizzas. When you select a pizza, it will return the selected pizza to the previous screen.

Step 1: Define Home Screen

This is the main screen of the application. It has a button to navigate to the pizza selection screen and a text widget to display the selected pizza.

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String? _selectedPizza;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Pizza Selection')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              child: Text('Select Pizza'),
              onPressed: () async {
                final selectedPizza = await Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => PizzaSelectionScreen()),
                );
                setState(() {
                  _selectedPizza = selectedPizza;
                });
              },
            ),
            SizedBox(height: 20),
            Text('Selected Pizza: $_selectedPizza'),
          ],
        ),
      ),
    );
  }
}
Step 2: Define Pizza Selection Screen

This screen displays a list of pizzas. When you select a pizza, it will return the selected pizza to the previous screen.

class PizzaSelectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Select Pizza')),
      body: ListView(
        children: [
          ListTile(
            title: Text('Margherita'),
            onTap: () {
              Navigator.of(context).pop('Margherita');
            },
          ),
          ListTile(
            title: Text('Pepperoni'),
            onTap: () {
              Navigator.of(context).pop('Pepperoni');
            },
          ),
          ListTile(
            title: Text('Vegetarian'),
            onTap: () {
              Navigator.of(context).pop('Vegetarian');
            },
          ),
        ],
      ),
    );
  }
}
Run Online

Challenge

Create a app with a HomeScreen and a ColorSelectionScreen. The HomeScreen should have a button to navigate to the ColorSelectionScreen where the user can select a color. Once a color is selected, the ColorSelectionScreen should return that color to the HomeScreen, which then changes its background color accordingly.

Available Colors:
- Red
- Blue
- Green