[英]Flutter - change icon color when selected
I'm trying to make a tab bar and have the icons be gray while selected and go back to black when a different icon is selected.我正在尝试制作一个标签栏,并在选择时将图标变为灰色,并在选择不同的图标时变回黑色。 My problem is however that upon clicking on one of icons, it registers the click, but I don't understand why it doesn't change the color of the icons.
然而,我的问题是,在单击其中一个图标时,它会注册点击,但我不明白为什么它不会改变图标的颜色。 Help would be greatly appreciated!
帮助将不胜感激!
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');},
),
use setState
to rebuild page使用
setState
重建页面
Make sure you are using statefull widget instead of stateless widget确保您使用的是有状态小部件而不是无状态小部件
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');},
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.