我试图制作一个标签栏,使图标在选中时为灰色,在选择其他图标时又变回黑色。但是我的问题是,在单击图标之一时,它会注册单击,但是我不明白为什么它不会更改图标的颜色。帮助将不胜感激!
int buttonSelected = 1;
IconButton(
icon: Icon(Icons.home, color: buttonSelected == 1 ? Colors.grey : Colors.black,),
onPressed: () {
buttonSelected = 1;
print('home');},
),
IconButton(
icon: Icon(Icons.message, color: buttonSelected == 2 ? Colors.grey : Colors.black,),
onPressed: () {
buttonSelected = 2;
print('message');},
),
最佳答案
使用setState
重建页面
确保您使用的是有状态小部件,而不是ajit强无状态小部件
int buttonSelected = 1;
IconButton(
icon: Icon(Icons.home, color: buttonSelected == 1 ? Colors.grey : Colors.black,),
onPressed: () {
setState(){ buttonSelected = 1;};
print('home');},
),
IconButton(
icon: Icon(Icons.message, color: buttonSelected == 2 ? Colors.grey : Colors.black,),
onPressed: () {
setState(){ buttonSelected = 2;};
print('message');},
),