Form input in Flutter

Text field widgets

In Flutter, use the TextEditingController class to manage a TextField widget. Whenever the text field is modified, the controller notifies its listeners.

Listeners read the text and selection properties to learn what the user typed into the field. You can access the text in TextField by the text property of the controller.

final TextEditingController _controller = TextEditingController();

TextField(
  controller: _controller,
  decoration: const InputDecoration(
    hintText: 'Type something',
    labelText: 'Text Field',
  ),
),
ElevatedButton(
  child: const Text('Submit'),
  onPressed: () {
    showDialog(
      context: context,
      child: AlertDialog(
        title: const Text('Alert'),
        content: Text('You typed ${_controller.text}'),
      ),
    );
  },
),

In this example, when a user clicks on the submit button an alert dialog displays the current text entered in the text field. This is achieved using an AlertDialog widget that displays the alert message, and the text from the TextField is accessed by the text property of the TextEditingController.

Form widgets

In Flutter, use the Form widget where TextFormField widgets along with the submit button are passed as children. The TextFormField widget has a parameter called onSaved that takes a callback and executes when the form is saved. A FormState object is used to save, reset, or validate each FormField that is a descendant of this Form. To obtain the FormState, you can use Form.of() with a context whose ancestor is the Form, or pass a GlobalKey to the Form constructor and call GlobalKey.currentState().

final formKey = GlobalKey();

Form(
  key: formKey,
  child: Column(
    children: [
      TextFormField(
        validator: (String value) => value.contains('@')
            ? null
            : 'Not a valid email.',
        onSaved: (String val) => _email = val,
        decoration: const InputDecoration(
          hintText: 'Enter your email',
          labelText: 'Email',
        ),
      ),
      ElevatedButton(
        onPressed: _submit,
        child: const Text('Login'),
      ),
    ],
  ),
)

The following example shows how Form.save() and formKey (which is a GlobalKey), are used to save the form on submit.

void _submit() {
  final form = formKey.currentState;
  if (form.validate()) {
    form.save();
    showDialog(
      context: context,
      child: AlertDialog(
        title: const Text('Alert'),
        content: Text('Email: $_email, password: $_password'),
      )
    );
  }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search