将数据从 AlertDialog 传递到同一屏幕

时间:2021-06-29 13:34:12

标签: flutter

我在简单地将数据从 AlertDialog 发送到我们的主屏幕 _MyHomePageState 和定义的 Text 小部件时遇到了一些麻烦,上面写着“粘贴到这里!”。

我也有一些关于在这种情况下传递数据的问题(我们将数据从弹出窗口发送到同一屏幕或其他屏幕):

1.) 在这种情况下使用 AlertDialog 小部件是否是正确的技术?

2.) 传递输入数据并显示它的正确方法是什么,我们是否先将其保存到数组中,然后从数组中检索值?我们使用堆栈还是其他一些数组方法?

3.) 为什么或为什么不应该将我的逻辑放入 _MyHomePage 类中,否则这无关紧要?

4.) 我应该使用从其他文件调用的自定义组件来弹出按钮/窗口吗? (感觉就像只有一堆代码明智的东西可以在它自己的文件中的其他地方单独存在)

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

GlobalKey<FormState> _formKey = GlobalKey<FormState>();

Future<void> showInformationDialog(BuildContext context) async {
  return await showDialog(context: context,
  builder: (context) {
    final TextEditingController _textEditingController = TextEditingController();
    bool isChecked = false;
    final TextEditingController _testEE = TextEditingController();

    return StatefulBuilder(builder: (context, setState) {
      return AlertDialog(
        content: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextFormField(
                  controller: _testEE,
                  validator: (value) {
                    //check if value is empty
                    return value.isNotEmpty ? null : "Invalid Field";
                  },
                  decoration: InputDecoration(hintText: "Enter text"),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text("Choice"),
                    Checkbox(value: isChecked, onChanged: (checked) {
                      setState((){
                        isChecked = checked;
                      });
                    })
                  ],
                )
              ],
            )),
        actions: <Widget>[
          TextButton(
            child: Text("Okay"),
            onPressed: () {
              var _test = _testEE.text;
              print("test?" + _test);
              if(_formKey.currentState.validate()) {
                Navigator.of(context).pop();
              }
            },
          )
        ],
      );
    });
  });
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.teal[800],
      body: ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 15.0, left: 40.0),
            child: Row(
              children: <Widget>[
                Text('Check List',
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 25.0)),
                IconButton(
                  padding: EdgeInsets.only(left: 140.0),
                  icon: Icon(Icons.menu),
                  color: Colors.white,
                  onPressed: () {},
                )
              ],
            ),
          ),
          SizedBox(height: 15.0),
          Container(
            height: MediaQuery.of(context).size.height - 100.0,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(topLeft: Radius.circular(75.0)),
            ),
            child: ListView(
              primary: false,
              padding: EdgeInsets.only(left: 35.0, right: 35.0),
              children: <Widget>[
                Padding(
                    padding: EdgeInsets.only(top: 25.0),
                    child: Container(
                        height: MediaQuery.of(context).size.height - 300.0,
                        child: ListView(children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 5.0),
                            child: Text('Test 1',
                              style: TextStyle(
                              fontFamily: 'Montserrat',
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 15.0)),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 5.0),
                            child: Text("Paste here!",
                                style: TextStyle(
                                    fontFamily: 'Montserrat',
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 15.0)),
                          ),
                          //_buildFoodItem('assets/plate5.png', 'Berry bowl', '\$24.00')
                        ]))),

                //Button Row
                Padding(
                  padding: const EdgeInsets.only(top: 60.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      SizedBox(
                        width: 75.0,
                        height: 75.0,
                        child: ElevatedButton(
                          onPressed: () async {
                            await showInformationDialog(context);
                          },
                          child: Text("Add"),
                          style: ElevatedButton.styleFrom(
                            side: BorderSide(width: 2.0, color: Colors.black),
                            shape: CircleBorder(),
                            padding: EdgeInsets.all(20),
                            primary: Colors.white, // <-- button color
                            onPrimary: Colors.black, // <-- splash color
                          ),
                        ),
                      ),

1 个答案:

答案 0 :(得分:0)

从推送的屏幕或对话框中返回参数很简单。 您使用的方法 pop() 接受一个可选的结果参数:

Navigator.pop(context, _test); // _test will be returned

该方法的文档可以阅读here

使用它返回上一屏幕所需的值。您需要使用 await 并将结果保存在变量中:

onPressed: () async {
                            String result = await showInformationDialog(context);
                            setState((){
                                      myText=result;
                            });
                          },

记得在 State 类中声明 myText

class _MyHomePageState extends State<MyHomePage> {
String myText = ''; // add this.

并在需要的地方使用此变量:

[...]
child: Text(myText,
[...]

您可以在 Flutter 团队的 this 食谱中阅读更多相关信息。

Ps:关于其他问题,大部分都是基于意见的。它们是项目决策,各有利弊。我相信,如果这是一个简单的项目,那就没有那么重要了。如果您需要更深入地研究这些主题,我建议您创建其他问题,因为它们与本主题无关。