skip to Main Content

So I have a TextFormField and a Checkbox. The Checkbox controls whether the TextFormField is enabled or disabled by setting the enabled parameter of the TextFormField.

The problem I am having is that if the TextFormField has an error message, the error message persists even after the enabled parameter is set to false. This is very confusing to the users. How can I clear the error message whenever I disable the TextFormField?

ListTile(
    leading: Checkbox(
        value: _enabled,
        onChanged: (value) =>
            setState(() => _enabled = value!)),
    title: TextFormField(
      enabled: _enabled,
      validator: (String? value) {
        if (value == null || value.isEmpty) {
          return "Please enter text";
        } else {
          return null;
        }
      },
    ),
  )

2

Answers


  1. You can make validator to check if Field is disabled

    if (value?.isEmpty ?? true && _enabled) {
      return "Please enter text";
    } else {
      return null;
    }
    
    Login or Signup to reply.
  2. you need to wrap your listtile in a form widget and after changing _enabled value, form state needs be reset, here is a simple code:

     Form(
              key: key,
              child: ListTile(
                  leading: Checkbox(
                    value: enabled.value,
                    onChanged: (value) {
                      enabled.value = value!;
                      key.currentState!.reset();
                      setState((){});
                    },
                  ),
                  title: TextFormField(
                    enabled: enabled.value,
                    validator: (String? value) {
                      if (value == null || value.isEmpty) {
                        return "Please enter text";
                      } else {
                        return null;
                      }
                    },
                  ),
                ),
              
            ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search