Checkbox form validation

前端 未结 4 2357
栀梦
栀梦 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: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(
      builder: (state) {
        return Column(
          children: [
            Row(
              children: [
                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;
        }
      },
    ),
    

提交回复
热议问题