【问题标题】:IconButton color does not change (Flutter)IconButton 颜色不会改变 (Flutter)
【发布时间】:2020-12-27 17:08:25
【问题描述】:

我有一个用于密码字段的 TextField 小部件和一个用于显示/隐藏密码的 IconButton。我想要的是当用户点击 IconButton 时,它应该改变颜色。实际上,当我在单击 IconButton 之前和之后运行 print(showPassWordIconColor) 时,它的值会发生变化。但是它不显示更改的颜色。 我看过其他一些问题和他们的答案,我试过了,但我仍然遇到同样的问题。 这是完整的小部件。 (最初 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);
        });
      },
    ),
  ),
);

【问题讨论】:

  • showPaswswordIconColor 方法在哪里?
  • 它是在文件顶部定义的颜色类型的变量。我可以到达它并在 setState() 中更改它,但显示的颜色没有改变。

标签: flutter iconbutton


【解决方案1】:

请检查以下代码。

然后使用下面的代码。

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);
                    });
                  },
                ),
              ),
            ),
          )

【讨论】:

  • 我已经将它们声明为文件顶部的变量,正如我所提到的,我可以在我的小部件中访问这些变量。我可以更新 _showPassword 和 showPasswordIconColor 变量。但我无法更新 IconButton 的可见颜色
  • 好的,不要检查这段代码,它已经在我的文件上编辑过
猜你喜欢
  • 2023-01-23
  • 2023-01-07
  • 2020-10-19
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多