【问题标题】:How can I use "showDialog" in order to propagate data backwards in Flutter?如何使用“showDialog”在 Flutter 中向后传播数据?
【发布时间】:2023-04-08 01:44:01
【问题描述】:
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 小部件?

【问题讨论】:

    标签: flutter dart async-await widget


    【解决方案1】:

    好吧,这几乎就是文档所说的,它在您的应用程序的当前内容上方显示了一个材质对话框,至于this,它将当前小部件作为对话框的子级传递,至于返回值就像正常的页面导航,当你调用pop(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),
          ),
        );
      }
    }
    

    【讨论】:

    • 是的,帮助我理解了一点。我会试试这个例子。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2022-07-17
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    相关资源
    最近更新 更多