[英]OnFieldSubmitted does not take the text value provided using TextFormField in Flutter
我正在尝试从文本字段中获取数据。 按下发送按钮时,我需要将文本字段中提供的数据存储在“_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);
},
),
)
)
],
您可以使用 _controller.text 获取当前文本字段中的值。
您需要像这样将文本传递给onFieldSubmitted: (_controller.text)
将解决问题。
你需要实现这个:
/// 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.
}
},
,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.