You are currently viewing How to Send Data From Dialog to Screen in Flutter?

How to Send Data From Dialog to Screen in Flutter?

β„Ή Introduction

How to send data from dialog to screen in Flutter apps. In Flutter we are given many tools to deal with many scenarios out of the box. Thankfully Flutter is packaged with Navigator class. Which handles the job of pushing and popping screens and dialogs to and from the navigation stack respectively. How can we use the Navigator class to send data from dialog to screen? That’s what we will learn today. So without any further delay let’s get right to it.

πŸ›  Implementation

Open Dialog

Now the first step is to create the calling function for the Dialog. This will be inside your screen that needs the data. In this example we will create an Elevated Button that will simply open the dialog and await the result from the dialog. Here’s the code for the button.

                ElevatedButton(
                  onPressed: () async {
                    final String result = await showDialog(
                      context: context,
                      builder: (context) => const DialogWidget(),
                    );

                    setState(() {
                      greetingText = result;
                    });
                  },
                  child: const Text("Select Greeting"),
                )

In the code above all we did is create and Elevated Button that has an async callback for it’s onPressed property. Clicking this button will open a Dialog and when the Dialog is closed it will return data. After the data is returned you can do whatever your use case requires. In this example I used the result to update the variable greetingText.

Return Data From Dialog To Screen

Now comes the second part of the solution. We will create a dialog widget in which user selection will send some data back to the parent screen. Below is the code for the Dialog widget.

class DialogWidget extends StatelessWidget {
  const DialogWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("Select Greeting"),
      actions: [
        TextButton(
            onPressed: () {
              Navigator.of(context).pop("Hi");
            },
            child: const Text("Hi")),
        TextButton(
            onPressed: () {
              Navigator.of(context).pop("Hello");
            },
            child: const Text("Hello"))
      ],
    );
  }
}

Basically what the above code does is that it uses the Navigator.of(context).pop() function to not only pop the dialog from navigation stack but an optional parameter is also accepted by pop function. It can be of any data type but in this case we’re just returning a string. Once user clicks either of those action buttons the data will be sent back to the parent screen and the greetingText variable will be updated

πŸ§ͺ Testing The Result

Below is the demo of what we discussed in this post.

πŸ’» Complete Source Code

Below is the complete source code of everything we discussed in this post.

import 'package:flutter/material.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomeWidget(),
    );
  }
}

class HomeWidget extends StatefulWidget {
  const HomeWidget({
    super.key,
  });

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  String greetingText = "Hello World";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(greetingText),
            const SizedBox(
              height: 25,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    final String result = await showDialog(
                      context: context,
                      builder: (context) => const DialogWidget(),
                    );

                    setState(() {
                      greetingText = result;
                    });
                  },
                  child: const Text("Select Greeting"),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class DialogWidget extends StatelessWidget {
  const DialogWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("Select Greeting"),
      actions: [
        TextButton(
            onPressed: () {
              Navigator.of(context).pop("Hi");
            },
            child: const Text("Hi")),
        TextButton(
            onPressed: () {
              Navigator.of(context).pop("Hello");
            },
            child: const Text("Hello"))
      ],
    );
  }
}

πŸ“ Conclusion

We used Flutter’s Navigator class to learn how we can send data from Dialog back to the parent screen. We used the pop method and provided and argument to it. That argument was our data that we wanted to return. Upon receiving the data the parent screen updated itself accordingly. That’s it for this post, if this post was helpful to you, you may like my other posts in the Flutter Archives. Thank you for reading.

Leave a Reply

Logged in as ammar629.Click to edit your profile Log out »