Home > OS >  Flutter TextField vs TextFormField
Flutter TextField vs TextFormField

Time:07-26

What is the difference between TextField and TextFormField in flutter? Both look the same. Which one should i use? Which one do you recommend? I use TextField like this:

const TextField(
  obscureText: true,
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Password',
  ),
)

CodePudding user response:

You use TextFormField when using Form widget. Combined with Form widget you can make more complex forms validation for whole form.

TextField is basically a TextFormField but you don't have to include it into the Form widget and validation would work a bit differently.

CodePudding user response:

A TextFormField mainly has the validator argument, while TextField doesn't: it must return null if the input is valid, and it must return a String if there's some error (usually the String itself contains information about the error). This argument allows you to validate the user input in a very easy way, provided that you include the form fields (there are others, in addition to TextFormField) in a Form widget and that you apply a Key to the Form.

If you do everything correctly, you could just invoke formKey.currentState!.validate() and automatically Flutter will invoke the validator argument for each form field that you added to the Form. If everything checks, the validate will return true, and you can proceed with your program logic. Otherwise, it will return false and it will show the String returned by the validator near the form field that contained incorrect data.

This example is taken from the Flutter cookbook on forms:

[...]
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter some text';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                // Validate returns true if the form is valid, or false otherwise.
                if (_formKey.currentState!.validate()) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Processing Data')),
                  );
                }
              },
              child: const Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}
  • Related