How to change IconButton based on a condition flutter?

2.7k views Asked by At

I want to change like button color if iconButton is pressed and when the listview is loading based on conditon iconButton color will be changed. I have a listview and in every row of listview i have a like iconButton. I need change the color from grey to blue onpress and When the listview will load again then i have whether liked before or not and based on this condition i have to change color.

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

how can i do this?

4

There are 4 answers

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

use a ternary operator.

1
Besufkad Menji On

check this

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
nvoigt On

I have difficulties understanding when you want to change the color.

You can change the color based on a variable like this:

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

assuming you have a boolean variable called _shouldBeRed.

Now you may need one such variable per list entry if you have one button per list entry. Maybe you already have that. Maybe you can add a field to your data model for the list. Maybe you just use a map of id and bool for all your ids you have and bools you need. You will need to figure that out, you did not give enough information for me to provide a good solution to that.

1
Salim Murshed On

You can check the code below. Use a bool.

bool checkBoxState = false;

Then,

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