Milan Poudel
Milan Poudel

Reputation: 792

How can I use "showDialog" in order to propagate data backwards in Flutter?

Future<bool> show(BuildContext context) async {
    return Platform.isIOS
    ? await showCupertinoDialog<bool>
    (context: context, builder: (context)=>this)
    :await showDialog<bool>(
      context: context,
      builder: (context) => this,
    );
  }

Can anyone help me to understand the term 'this',what does 'this' refer to and how does showDialog works that it returns Future.I tried to read documentation but still couldn't understand it?Is it the same as AlertDialog widget?

Upvotes: 0

Views: 333

Answers (1)

hewa jalal
hewa jalal

Reputation: 961

well, it's pretty much what the documentation said, it shows a material dialog above the current content of your app, as for this it passes the current widget as child for the dialog, as for the returned value is just like normal page navigation that when you call pop(context, {value}) method you can also return a value, so that value that inside pop will be returned from the dialog.

here is an example below:

class DialogTest extends StatefulWidget {
  @override
  _DialogTestState createState() => _DialogTestState();
}

class _DialogTestState extends State<DialogTest> {
// the value that will be typed to the dialog
  String dialogText;
// the value that will be returned from the dialog
  String returnedFromDialog;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sample Code'),
      ),
      body: Center(
        child:
            Text('You got this value from the dialog => $returnedFromDialog'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          returnedFromDialog = await showDialog<String>(
              context: context,
              builder: (context) {
                return AlertDialog(
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      TextField(
                        onChanged: (value) => dialogText = value,
                      ),
                      FlatButton(
                        onPressed: () {
                          setState(() => Navigator.pop(context, dialogText));
                        },
                        child: Text(
                          'Close dialog',
                          style: TextStyle(color: Colors.red),
                        ),
                      )
                    ],
                  ),
                );
              });
        },
        child: Icon(Icons.open_in_browser),
      ),
    );
  }
}

the results

Upvotes: 1

Related Questions