Home > Net >  What is the right way to change icon from selected to unselected in Flutter?
What is the right way to change icon from selected to unselected in Flutter?

Time:02-04

I am creating add to cart logic, so I created a function which is added items in the cart, but I don't understand how properly change icons from unselected to selected. So I was trying to do something like that:

 void addToCart(Item prod) {
    print('it works');
    products.add(prod);
    print('it works2');
  }

  Widget iconChage(){
    if(_isPressed == true){
      return Icon(Icons.ten_k);
    }else{

      return Icon(Icons.eleven_mp);
    }

But it doesn't work when I put it to the widget tree. What is the right way to change the icon from selected to unselected?

CodePudding user response:

Try this way:

Make a bool to use as condition:

bool isPressed = true;

Then use your icon like this:

Icon(isPressed? Icons.ten_k : Icons.eleven_mp)

When want to toggle the icon just simply do this:

setState(()=> isPressed = !isPressed)
  •  Tags:  
  • Related