Flutter: How to pass data back from a dialog box

It goes both ways

Aditya Chakraborti
2 min readMay 29, 2020
Sum of Flutter and Dialog boxes.

A couple of days ago, while I was working on a project, wherein I had a custom stateful dialog box that rendered a form, I wanted to pass data from the form, back to the calling function.

Now, I had never done this before, so I did what most developers would do, a simple Google search. There were some solutions available for a few similar cases, but nobody seemed to be talking about this particular situation. Sure, I found out that you can pass data back with a Navigator.pop(), but what can I pass it back to?

Navigator.pop(context, "Pass your data here");

In this article by the Flutter team, they demonstrate passing data, back from another screen, by waiting for the Navigator.push() method to return data that’ll be returned by Navigator.pop() as shown above, but nowhere is anyone talking about how to do this in the case of a dialog box. By this point, I was wondering whether I was missing something very fundamental that everyone else knew.

My next move would’ve probably been using callbacks to pass my data, (let me know in the comments if you would like to know how to do that), but I decided that I ‘ll give the documentation a go before I end up doing that.

So, in the documentation page for the showDialog() function, it specifies

Returns a Future that resolves to the value (if any) that was passed to Navigator.pop when the dialog was closed.

And that’s it. That’s all I need. Now I can just wait for the dialog to send data back.

Code Snippets

The calling function side

Passing data is simple. We can pass data as a parameter, and then we wait for the future returned by the dialog and store it in a variable.

var data = await showDialog(
context: context,
child: MyCustomDialog(
parameterName: "A Random Parameter",
),
);

The dialog box side

Here, we pass data back to the calling function above on the press of a button.

RaisedButton(
child: Text("Submit"),
onPressed: () {
String text = "Data that we want to pass. Can be anything.";
Navigator.pop(context, text);
},
)

That’s it. That’s the minimum you need to do this.

I hope this saved you some time.

if it did:
leave a clap
if you have any similar stories that you wanna share:
leave a comment or reach out to me on LinkedIn or via e-mail.

--

--