我正在尝试在我的应用中解决表单验证。每次单击TextFromField时,焦点都会丢失,键盘会隐藏。我发现问题在于“_formKey”。但我需要它来验证。怎么解决?
代码段
class _TodoCreateDetailPageState extends State<TodoPage> {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
String _title = widget.todo == null ? "New TODO" : widget.todo.title;
String _message;
return new Scaffold(
appBar: new AppBar(
title: new Text(_title),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.save), onPressed: null),
body: new Padding(
padding: new EdgeInsets.all(20.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new TextField(
decoration: new InputDecoration(labelText: 'Title'),
onChanged: (String value) {
_title = value;
},
),
new TextField(
decoration: new InputDecoration(labelText: 'Message'),
onChanged: (String value) {
_message = value;
},
)
],
))),
);
}
答案 0 :(得分:1)
正如Derek Lakin在评论中所说,将StatelessWidget
更改为StatefulWidget
对我有用。
答案 1 :(得分:1)
您似乎知道问题出在密钥本身,例如#6783。解决方案是避免每次构造验证密钥。因此,您可以这样进行操作(甚至使其成为小部件的属性):
class _TodoCreateDetailPageState extends State<TodoPage> {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
String _title = widget.todo == null ? "New TODO" : widget.todo.title;
String _message;
return new Scaffold(
appBar: new AppBar(
title: new Text(_title),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.save), onPressed: null),
body: new Padding(
padding: new EdgeInsets.all(20.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new TextField(
decoration: new InputDecoration(labelText: 'Title'),
onChanged: (String value) {
_title = value;
},
),
new TextField(
decoration: new InputDecoration(labelText: 'Message'),
onChanged: (String value) {
_message = value;
},
)
],
))),
);
}
答案 2 :(得分:0)
我遇到了同样的问题,并且找到了解决方案,只需在build方法之外定义一个控制器变量即可。 使用TextEditingController()
答案 3 :(得分:-1)
尝试将焦点节点提供给文本字段。
new TextField(focusNode: new FocusNode(),
答案 4 :(得分:-1)
此问题是由于在build()中使用了GlobalKey初始化
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
//this will work fine when you move key outside the build();
@override
Widget build(BuildContext context){
}
从构建中删除它,一切都很好。
{
"key": "ctrl+k ctrl+k",
"when": "editorTextFocus",
"command": "selectby.lineNr",
"args": { "lineNrEx": "c-n==10" }
},
{
"key": "ctrl+k ctrl+j",
"when": "editorTextFocus",
"command": "selectby.lineNr",
"args": { "lineNrEx": "n-c==10" }
}