首页 > 解决方案 > 按下按钮时如何更改文本颜色?

问题描述

我在按下按钮时出现颜色变化问题,我设置了布尔条件,一切都很好,但文本的颜色没有改变?

我的代码:

    TextButton(
            onPressed: () {
              setState(() {
                pressed = !pressed;
              });
            },
            child: Container(
              margin: const EdgeInsets.all(8),
              height: 60,
              width: 340,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(15),
              ),
              alignment: Alignment.center,
              child: Text(
                'Suivant',
                style: pressed
                    ? TextStyle(color: Colors.grey)
                    : TextStyle(color: Colors.red),
              ),
            ),
          ),

标签: flutterdart

解决方案


代码对我来说工作正常。我只能猜测是什么错误。

也许您的pressed变量是在build()方法内部声明的,而不是在State类内部声明的。

尝试将声明移至类级别,它应该可以正常工作


推荐阅读