Checkbox form validation

前端 未结 4 2673
栀梦
栀梦 2021-02-20 11:27

How can I validate a checkbox in a Flutter Form? Every other validation works fine, but the checkbox doesn\'t show an Error. Here is my code:

FormFi         


        
4条回答
  •  没有蜡笔的小新
    2021-02-20 12:13

    A cleaner solution to this problem is to make a class that extends FormField

    Here is how I accomplished this:

    class CheckboxFormField extends FormField {
      CheckboxFormField(
          {Widget title,
          FormFieldSetter onSaved,
          FormFieldValidator validator,
          bool initialValue = false,
          bool autovalidate = false})
          : super(
                onSaved: onSaved,
                validator: validator,
                initialValue: initialValue,
                autovalidate: autovalidate,
                builder: (FormFieldState state) {
                  return CheckboxListTile(
                    dense: state.hasError,
                    title: title,
                    value: state.value,
                    onChanged: state.didChange,
                    subtitle: state.hasError
                        ? Builder(
                            builder: (BuildContext context) =>  Text(
                              state.errorText,
                              style: TextStyle(color: Theme.of(context).errorColor),
                            ),
                          )
                        : null,
                    controlAffinity: ListTileControlAffinity.leading,
                  );
                });
    }
    

提交回复
热议问题