简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM