IconButton color does not change (Flutter)

1k views Asked by At

I have a TextField widget for a password field and an IconButton for showing/hiding the password. What I want is that when the user taps on the IconButton, it should change color. It does actually, when I run print(showPassWordIconColor) before and after clicking the IconButton, its value changes. However it does not display the changed color. I have seen some other questions and their answers, and I tried them but I still get the same problem. Here is the full widget. (initially showPasswordIconColor = Colors.grey)

Widget passwordField = AppTextFormField(
  obscureText: !_showPassword,
  decoration: InputDecoration(
    hintText: "Password",
    border: OutlineInputBorder(),
    suffixIcon: IconButton(
      icon: Icon(
        Icons.remove_red_eye,
        color: showPasswordIconColor,
      ),
      onPressed: () {
        setState(() {
          _showPassword = !_showPassword;
          if (showPaswswordIconColor == Colors.grey) {
            showPaswswordIconColor = buttonColor;
          } else {
            showPaswswordIconColor = Colors.grey;
          }
          print(showPaswswordIconColor);
        });
      },
    ),
  ),
);
2

There are 2 answers

2
Salim Murshed On

enter image description herePlease check the below code.

Then use the below code.

Container(
            width: 200,
            height: 200,
            child: TextFormField(
              obscureText: !_showPassword,
              decoration: InputDecoration(
                hintText: "Password",
                border: OutlineInputBorder(),
                suffixIcon: IconButton(
                  icon: Icon(
                    Icons.remove_red_eye,
                    color: showPasswordIconColor,
                  ),
                  onPressed: () {
                    setState(() {
                      _showPassword = !_showPassword;
                      if (showPasswordIconColor == Colors.grey) {
                        showPasswordIconColor = Colors.red;
                      } else {
                        showPasswordIconColor = Colors.grey;
                      }
                      print(showPasswordIconColor);
                    });
                  },
                ),
              ),
            ),
          )
0
Waldson Fagundes On

If you are using ThemeData you can apply a schema like this.

inputDecorationTheme: InputDecorationTheme(
        iconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
          if (states.contains(MaterialState.focused)) {
            return Colors.green;
          }
          if (states.contains(MaterialState.error)) {
            return Colors.red;
          }
          return Colors.green;
        }
        ),
      )