Flutter Web 在回车键上提交表单

Flutter Web submit form on enter key

有没有办法在用户填写表单时点击回车按钮时调用提交按钮。这是我的表单代码:

@override
  Widget build(BuildContext context) {
    String _email;
    return AlertDialog(
      title: Text('Password Reset'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              decoration: InputDecoration(
                hintText: 'Email',
                labelText: 'Email',
              ),
              autofocus: true,
              maxLength: 30,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Email is required';
                }
                return null;
              },
              onSaved: (input) => _email = input,
            ),
          ],
        ),
      ),
      actions: [
        RaisedButton(
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              var result = await auth.sendPasswordResetEmail(_email);
              print(result);
              Navigator.of(context).pop();
            }
          },
          child: Text('Reset'),
        )
      ],
    );
  }

根据您的需要,使用 TextFormField 构造函数的 onEditingComplete or onSubmitted 参数。

对于 TextFormField,要处理此问题的 属性 将是 onFieldSubmitted。您可以将 RaiseButtononPressed 中的代码复制到此。例如

onFieldSubmitted: (value) {
                if (_formKey.currentState.validate()) {
                  _formKey.currentState.save();
//               var result = await auth.sendPasswordResetEmail(_email);
//               print(result);
                  print(_email);
                  Navigator.of(context).pop();
                }
              },

一个完整的例子可以作为 codepen here

You might be interested in RawKeyboardListener as well however it doesn't recognize the enter key. But could listen to other keys such as Shift, CapsLock etc.