Flutter form clear validation

Flutter Form Clear Validation

When working with forms in Flutter, you can use the Form class along with various form field widgets for input validation. To clear the validation errors from a form, you can utilize the key property of the Form widget and a GlobalKey.

Step 1: Define a GlobalKey for the Form


    GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  

Create a GlobalKey object with the FormState type. This key will uniquely identify the form.

Step 2: Assign the GlobalKey to the Form


    Form(
      key: _formKey,
      // other form fields
    )
  

In your Form widget, provide the key property with the GlobalKey object.

Step 3: Clear Form Validation Errors


    _formKey.currentState.reset();
  

To clear the validation errors from the form, access the currentState property of the _formKey and call the reset() method.

Example:


    import 'package:flutter/material.dart';

    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      GlobalKey<FormState> _formKey = GlobalKey<FormState>();

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Form Clear Validation Example'),
            ),
            body: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'This field is required';
                      }
                      return null;
                    },
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (_formKey.currentState.validate()) {
                        // form is valid, proceed
                      }
                    },
                    child: Text('Submit'),
                  ),
                  RaisedButton(
                    onPressed: () {
                      _formKey.currentState.reset(); // clear form validation errors
                    },
                    child: Text('Clear Validation'),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
  

In this example, a basic form is created with a TextFormField and two RaisedButton widgets. The TextFormField has a validator function to check if the input is empty. The first RaisedButton is used to submit the form data if it passes validation. The second RaisedButton is used to clear the validation errors by calling the reset() method on the form’s GlobalKey.

Leave a comment