0

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

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

我怎样才能做到这一点?

4

4 回答 4

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

使用ternary运算符。

于 2020-10-01T17:44:00.423 回答
2

检查这个

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();
 },
),
于 2020-10-01T17:44:06.633 回答
2

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

您可以根据如下变量更改颜色:

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

假设您有一个名为_shouldBeRed.

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

于 2020-10-01T17:44:23.173 回答
1

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

bool checkBoxState = false;

然后,

IconButton(
  icon: new Icon(Icons.thumb_up),
  color: checkBoxState ? Colors.blue: Colors.grey,
  onPressed: () {
    documentId = list[index].id;
    _incrementCounter();
  },
)
于 2020-10-01T17:51:34.310 回答