Search code examples
flutterdarttextfield

How can i make a suffixIcon in a TextField which hides if TextField is empty but shows when not and toggles a bool to hide and show password?


I have a TextField() for a Password Input. The sufficIcon, which is an eye, should only be shown, when TextField is not empty but it should also toogle a bool, so that user can hide and show password. It should show different suffixIcon, when password is shown or hidden.

This is my code for now:

bool isPasswordVisible = true;

IconButton(
          icon: isPasswordVisible
              ? const Icon(Icons.visibility)
              : const Icon(Icons.visibility_off),
          onPressed: () {
            setState(() {
              isPasswordVisible = !isPasswordVisible;
            });
          },
        ),

Solution

  • You can try this: Declare a boolean variable:

    bool isIconVisible = false;
    bool hidePassword = true;
    

    then in the TextField use the property onChanged:

    TextField(
      onChanged: (value) {
         //try this
         value.isNotEmpty ? setState(() => isIconVisible = true) : setState(() => isIconVisible = false);
         //or
         setState(() => value.isNotEmpty ? isIconVisible = true : isIconVisible = false);
         //the result is the same it's just a shortcode
      },
      obscureText: hidePassword,
      decoration: InputDecoration(
            labelText: 'Password',
            suffixIcon:  isIconVisible ? IconButton(
                 onPressed: (){
                        setState(() => hidePassword = !hidePassword);
                        },
                 icon:  Icon(
                      hidePassword ? 
                      Icons.visibility_off : Icons.visibility,
                        ),
           ) : null,
        ),
    );