Kishan Somaiya
Kishan Somaiya

Reputation: 192

Flutter/Dart :How to add validation to radio button like TextFormField?

How can I add validation to Radio Button in Flutter? I know there's a package called flutter_form_builder but I don't want to use it. Is there any way to add validation to the radio button? I would like it to validate it using formkey and I can't post code because the whole form is dynamic and I don't have permission to post the code online so any help is appreciated. Can I make a custom radio button?

Upvotes: 3

Views: 3394

Answers (1)

Meiliany Pranolo
Meiliany Pranolo

Reputation: 81

I know it is a bit late. Just use FormBuilder, for example.

or if you use it inside Form(), this is an example:

FormField(
                builder: (FormFieldState<bool> state) {
                  return Padding(
                      padding: EdgeInsets.all(10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Where is occurrence happened?'),
                          state.hasError
                              ? Text(
                                  state.errorText,
                                  style: TextStyle(color: Colors.red),
                                )
                              : Container(),
                          RadioListTile(
                            ...
                            onChanged: (SomeValueType value) {
                              ...                              
                              state.setValue(true);
                            },
                          ),
                          RadioListTile(
                            ...
                          ),
                        ],
                      ));
                },
                validator: (value) {
                  if (value != true) {
                    return 'Please choose location';
                  }
                  return null;
                },
              )

in that code, the validator will run when you call FormState.validate(), and then show the ErrorText.

Upvotes: 8

Related Questions