Flutter 颤振-选择后更改图标颜色
我正在尝试创建一个选项卡栏,当选择图标时图标为灰色,当选择其他图标时返回黑色。然而,我的问题是,当点击其中一个图标时,它会注册点击,但我不明白为什么它不会改变图标的颜色。非常感谢您的帮助Flutter 颤振-选择后更改图标颜色,flutter,dart,Flutter,Dart,我正在尝试创建一个选项卡栏,当选择图标时图标为灰色,当选择其他图标时返回黑色。然而,我的问题是,当点击其中一个图标时,它会注册点击,但我不明白为什么它不会改变图标的颜色。非常感谢您的帮助 int buttonSelected = 1; IconButton( icon: Icon(Icons.home, color: buttonSelected == 1 ? Colors.grey : Colors.black,), onPressed: () { buttonSelecte
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
重建页面
确保使用的是statefull小部件,而不是无状态小部件
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');},
),
更改选项卡时,您需要调用setState func。您也可以尝试TabBar的选项,即TabBar(
labelColor:YourColor,unselectedLabelColor:YourColor,
)使用状态完整的小部件。