0

Whenever I am defining the obscureText property of the TextFormField a suffix icon is automatically added at the end but after pressing it nothing happen,
The prefix icon is defined by me but the suffix icon is added automatically.
How to make that default icon interactive so that the password will be shown or hidden accordingly without adding our own suffix icon?

TextFormField(
  style: TextStyle(color: Colors.black),
  obscureText: true,
  decoration: InputDecoration(
    hintText: "Enter Password",
    labelText: "Password",
    prefixIcon: Icon(Icons.lock),
  ),
),

enter image description here enter image description here

G1Joshi
  • 73
  • 2
  • 9

3 Answers3

1

This is because you are not changing the state of the obsecuretext. In order to do that please declare variable of boolean type in main class.

  bool isPassword = false;

Now in obscureText use the variable which you declared in main class as below.

`obscureText = isPasswordVisible`

Now make a Icon button to change the state of the boolean value by using set state as below.

suffixIcon: IconButton(
  onPressed: () {
    setState(() {
      isPasswordVisible = !isPasswordVisible
    });
  },
  icon: isPasswordVisible  ? Icon(Icons.any_icon_you want) : Icon(Icons.any_Icon_you_want_to_display_when_obsecure_is_false)
),
Raju Gupta
  • 752
  • 5
  • 10
0
 suffixIcon: IconButton(
      onPressed: () => ShowHideFuncion(),
      icon: Icon(Icons.YourIcon),
    ),
Giorgi
  • 141
  • 1
  • 4
0

you need to make a variable in your widget of type bool (e.g. obscure). You then change the obscureText parameter from being true to being the variable you made. Then add a suffixIcon with an IconButton() (see more here). In the IconButton()'s onPressed parameter set the variable to be not equal to the variable. (e.g. obscure = !obscure). There is a possibility you might need to make your widget a stateless widget and call setState(() => obscure = !obscure) if it doesn't update automatically.

The final code should look something like this:


Icon icon = Icon(Icons.visibility);
bool obscure = true;

TextFormField(
  style: TextStyle(color: Colors.black),
  obscureText: obscure,
  decoration: InputDecoration(
    hintText: "Enter Password",
    labelText: "Password",
    suffixIcon: IconButton(
      onPressed: () {
        setState(() {
          if (obscure == true) {
            obscure = false;
            icon = Icon(Icons.visibility_off);
          } else {
            obscure = true;
            icon = Icon(Icons.visibility);
          }
        });
      },
      icon: icon
    ),
  ),
),