如何根据条件变化更改IconButton?

问题描述

如果要按iconButton,我想像按钮颜色一样进行更改,并且基于条件加载listview时,iconButton的颜色将被更改。 我有一个列表视图,并且在列表视图的每一行中都有一个类似iconButton的图标。我需要将颜色从onpress的灰色更改为蓝色,并且当再次加载listview时,我是否之前喜欢过,并且根据这种情况我必须更改颜色。

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

我该怎么做?

解决方法

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

使用ternary运算符。

,

检查此

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

当您要更改颜色时,我很难理解。

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

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

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

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

,

您可以检查以下代码。使用布尔。

bool checkBoxState = false;

然后

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