Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate TextFormField from another class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
                             }
)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading