【问题标题】:OnFieldSubmitted does not take the text value provided using TextFormField in FlutterOnFieldSubmitted 不接受 Flutter 中使用 TextFormField 提供的文本值
【发布时间】:2020-02-03 19:08:59
【问题描述】:

我正在尝试从文本字段中获取数据。按下发送按钮时,我需要将文本字段中提供的数据存储在“_message”中。这没有按预期工作,因此我的 Map(newMessage) 不包含任何值,因此我的消息列表为空。 我需要一些解决方案,以便我的 _message 保存使用 OnFieldSubmitted 提供的值。

即使在运行应用程序时,它也只会打印(发送“文本框中写入的值”),而不会打印使用 OnFeildSubmitted 提供的 _message。

 Padding(
        padding: EdgeInsets.all(12.0),
        child: Row(
          children: <Widget>[
            Expanded( 
                child: TextFormField(
              controller: _controller,
              onFieldSubmitted: (String _message){
                print("on submit  "+_message);
                Map<String,dynamic> newMessage = {
                  "type": "string",
                  "content": _message,
                  "from": "me",


                };
                List<dynamic> newList = _listOfMessages;
                newList.add(newMessage);

                setState(() {
                  _listOfMessages = newList;
                });
                _controller.clear();

              },
              decoration: InputDecoration(
                hintText: "Type your message here",
              ),
            )),
            Padding(
              padding: EdgeInsets.all(8.0),

              child: Center(
                child: IconButton(
                icon: Icon(Icons.send,
                color: Colors.blue),

                onPressed: () {
                  print("send " + _controller.text);
                },
              ),
              )
            )
          ],

【问题讨论】:

  • 如果 onPressed 代码正常工作,为什么不把 onFieldSubmitted 代码也移到那里?你想用 onFieldSubmitted 实现什么? PS。我没有记下你。
  • @GrahamD 很抱歉,因为我是这个颤振开发的新手。感谢您的帮助,它确实有效。
  • 不用担心。我们都在学习。

标签: java android flutter dart


【解决方案1】:

当前可以使用_controller.text获取Textfield中的值。

【讨论】:

【解决方案2】:

您需要将文本传递给onFieldSubmitted: (_controller.text),这样可以解决问题。

【讨论】:

    【解决方案3】:

    你需要实现这个:

    /// In `State` class body
    String _message;
    final _formKey = GlobalKey<FormState>();
    
    /// In `build` method body.
    Form(
      key: _formKey,        // <-- This is required.
      child: TextFormField(
        controller: _controller,
        onSave: (value) {
          _message = value;
        }
      ),
    ),
    
    IconButton(
      icon: Icon(
        Icons.send,
        color: Colors.blue
      ),
      onPressed: () {
        if(_formKey.currentState.validate()) {
          _formKey.currentState.save(); // This call triggers `onSave` callbacks.
          _sendMesage(_message);        // Handle _message variable.
        }
      },
    ,
    
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 2021-10-29
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      相关资源
      最近更新 更多