Checkbox form validation

前端 未结 4 2386
栀梦
栀梦 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<bool>

    Here is how I accomplished this:

    class CheckboxFormField extends FormField<bool> {
      CheckboxFormField(
          {Widget title,
          FormFieldSetter<bool> onSaved,
          FormFieldValidator<bool> validator,
          bool initialValue = false,
          bool autovalidate = false})
          : super(
                onSaved: onSaved,
                validator: validator,
                initialValue: initialValue,
                autovalidate: autovalidate,
                builder: (FormFieldState<bool> 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,
                  );
                });
    }
    
    0 讨论(0)
  • 2021-02-20 12:14

    You could try something like this :

    CheckboxListTile(
      value: checkboxValue,
      onChanged: (val) {
        setState(() => checkboxValue = val
      },
      subtitle: !checkboxValue
          ? Text(
              'Required.',
              style: TextStyle(color: Colors.red),
            )
          : null,
      title: new Text(
        'I agree.',
        style: TextStyle(fontSize: 14.0),
      ),
      controlAffinity: ListTileControlAffinity.leading,
      activeColor: Colors.green,
    );
    
    0 讨论(0)
  • 2021-02-20 12:23

    in case if you want to put your checkbox directly in your Form widget tree you can use solution provided below with FormField widget. Instead of using ListTile I used rows and columns as my form was requiring different layout.

    FormField<bool>(
      builder: (state) {
        return Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Checkbox(
                  value: checkboxValue,
                  onChanged: (value) {
                    setState(() {
    //save checkbox value to variable that store terms and notify form that state changed
                      checkboxValue = value;
                      state.didChange(value);
                    });
                  }),
                Text('I accept terms'),
              ],
            ),
    //display error in matching theme
            Text(
              state.errorText ?? '',
              style: TextStyle(
                color: Theme.of(context).errorColor,
              ),
            )
          ],
        );
      },
    //output from validation will be displayed in state.errorText (above)
      validator: (value) {
        if (!checkboxValue) {
          return 'You need to accept terms';
        } else {
          return null;
        }
      },
    ),
    
    0 讨论(0)
  • 2021-02-20 12:26

    The above answer is correct, however, if you want to display an error message that is more consistent with the default layout of a TextFormField widget error message, then wrap the Text widget in a Padding widget, and give it the hex colour #e53935.

    Note: You may need to adjust the left padding to fit the CheckboxListTile widget is also wrapped in a Padding widget.

    Check the code below:

        bool _termsChecked = false;
        CheckboxListTile(
                  activeColor: Theme.of(context).accentColor,
                  title: Text('I agree to'),
                  value: _termsChecked,
                  onChanged: (bool value) => setState(() => _termsChecked = value),
                  subtitle: !_termsChecked
                    ? Padding(
                        padding: EdgeInsets.fromLTRB(12.0, 0, 0, 0), 
                        child: Text('Required field', style: TextStyle(color: Color(0xFFe53935), fontSize: 12),),)
                    : null,
                ),
    
    0 讨论(0)
提交回复
热议问题