Search code examples
flutterflutter-web

Flutter Web submit form on enter key


Is there a way to call the submit button when a user hits the enter button when filling out a form. Here is my form code:

@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'),
        )
      ],
    );
  }

Solution

  • For a TextFormField the property to handle this would be onFieldSubmitted. You can copy the code from your onPressed of the RaiseButton to this. For e.g.

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

    A full example is available as a 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.