Validate TextFormField from another class

Issue

I have 2 statefull class, first class contains TextFormField and button to validate the TextFormField. And the second class contains TextFormField.

How to validate second TextFormField thats called in first class when tap the button?

class FormValidation extends StatefulWidget {
  const FormValidation({Key key}) : super(key: key);

  @override
  _FormValidationState createState() => _FormValidationState();
}

class _FormValidationState extends State<FormValidation> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                validator: (value) =>
                    value.isEmpty ? 'Field 1 cannot be Empty' : null,
              ),
              SecondForm(),
              ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState.validate()) {
                      print('DataSubmitted');
                    }
                  },
                  child: Text('Submit'))
            ],
          ),
        ),
      ),
    );
  }
}

and the second form

class SecondForm extends StatefulWidget {
  const SecondForm({Key key}) : super(key: key);

  @override
  _SecondFormState createState() => _SecondFormState();
}

class _SecondFormState extends State<SecondForm> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: TextFormField(
          validator: (value) =>
              value.isEmpty ? 'Field 2 cannot be Empty' : null),
    );
  }
}

Solution

add this on secondForm class, updated the validator with function widget

final Function(String)? validators; //initialization 

validator: widget.validators as String? Function(String?)?,

inside the FormValidation class call this function ,like this way

SecondForm(
validators: (String? value) {
           if (value!.isEmpty)
                return 'Required field';
                             }
)

Answered By – Jinto Joseph

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *