首页 > 解决方案 > 如何使用“showDialog”在 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,
    );
  }

谁能帮我理解“this”这个词,“this”指的是什么以及它返回 Future 的 showDialog 如何工作。我试图阅读文档但仍然无法理解它?它与 AlertDialog 小部件相同吗?

标签: flutterdartasync-awaitwidget

解决方案


好吧,这几乎是文档所说的,它在您的应用程序的当前内容上方显示了一个材质对话框,因为this它将当前小部件作为对话框的子项传递,至于返回的值就像正常的页面导航一样,当您callpop(context, {value})方法也可以返回一个值,这样pop里面的值就会从对话框中返回。

下面是一个例子:

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),
      ),
    );
  }
}

结果


推荐阅读