【问题标题】:How to change IconButton based on a condition flutter?如何根据条件抖动更改 IconButton?
【发布时间】:2021-01-17 11:28:17
【问题描述】:

如果 iconButton 被按下,我想改变按钮颜色,并且当基于条件加载列表视图时 iconButton 颜色将被改变。 我有一个列表视图,并且在列表视图的每一行中我都有一个类似的图标按钮。我需要在按下时将颜色从灰色更改为蓝色,当列表视图再次加载时,我知道之前是否喜欢,并且基于此条件我必须更改颜色。

new IconButton(
 icon: new Icon(Icons.thumb_up),
 color: Colors.grey,
   onPressed: (){
     documentId = list[index].id;
      _incrementCounter();
    },
   ),

我该怎么做?

【问题讨论】:

    标签: flutter colors icons iconbutton


    【解决方案1】:

    检查一下

    new IconButton(
     icon: new Icon(Icons.thumb_up),
     //check here for your condition and switch the color as you want
     color: yourCondition?Colors.blue:Colors.grey,
     onPressed: (){
       documentId = list[index].id;
       _incrementCounter();
     },
    ),
    

    【讨论】:

    【解决方案2】:

    当你想改变颜色时,我很难理解。

    您可以根据这样的变量更改颜色:

    color: _shouldBeRed ? Colors.red : Colors.grey,
    

    假设您有一个名为 _shouldBeRed 的布尔变量。

    现在,如果每个列表条目有一个按钮,则每个列表条目可能需要一个这样的变量。也许你已经有了。也许您可以在列表的数据模型中添加一个字段。也许您只是为您拥有的所有 id 和所需的 bool 使用 id 和 bool 的映射。您需要弄清楚这一点,您没有提供足够的信息让我提供一个好的解决方案。

    【讨论】:

    【解决方案3】:
    new IconButton(
     icon: new Icon(Icons.thumb_up),
     color:isPressed ? Colors.blue : Colors.grey,
       onPressed: (){
         documentId = list[index].id;
          _incrementCounter();
        },
       ),
    

    使用ternary 运算符。

    【讨论】:

    【解决方案4】:

    您可以查看下面的代码。使用布尔值。

    bool checkBoxState = false;
    

    那么,

    IconButton(
      icon: new Icon(Icons.thumb_up),
      color: checkBoxState ? Colors.blue: Colors.grey,
      onPressed: () {
        documentId = list[index].id;
        _incrementCounter();
      },
    )
    

    【讨论】:

    猜你喜欢
    • 2021-02-07
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多