如何改变文本颜色时,按下扑动按钮?



我有一个按钮按下颜色变化的问题,我做了bool条件,一切都很好,但文本的颜色没有改变?

my code:

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

您的代码运行良好。你只是第一个按下的变量初始值为false。

Try check this Code:

class Home extends StatefulWidget {
const Home({ Key? key }) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool pressed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: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),
),
),
),
),
);
}
}

代码对我来说工作得很好。我只能猜错在哪里。

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

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

最新更新