【问题标题】:Flutter - change icon color when selectedFlutter - 选择时更改图标颜色
【发布时间】:2020-08-26 12:11:21
【问题描述】:

我正在尝试制作一个标签栏,并在选择时让图标为灰色,并在选择其他图标时返回黑色。然而,我的问题是,在单击其中一个图标时,它会注册单击,但我不明白为什么它不会改变图标的​​颜色。非常感谢您的帮助!

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');},
),

【问题讨论】:

  • Tab 为 Change 时需要调用 setState 函数。
  • 你也可以试试 TabBar 选项 TabBar(labelColor: YourColor, unselectedLabelColor: YourColor,)
  • 使用有状态的小部件。

标签: flutter dart


【解决方案1】:

使用setState重建页面

确保您使用的是 statefull 小部件而不是 stateless 小部件

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');},
),

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 2015-06-01
    • 2021-08-07
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多