Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'),
        )
      ],
    );
  }
like image 572
DRing Avatar asked Jun 16 '20 22:06

DRing


2 Answers

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.

like image 165
Abhilash Chandran Avatar answered Oct 13 '22 16:10

Abhilash Chandran


Use either the onEditingComplete or onSubmitted parameters of the TextFormField constructor, depending on your needs.

like image 35
Gregory Conrad Avatar answered Oct 13 '22 16:10

Gregory Conrad