I am creating add to cart logic, so I created function which is added items in cart, but I don't understand how properly change icon from unselected to selected. So I 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 dosen't work when I put it to the widget tree. What is the right way to change icon fron selected to unselected?
I am trying that solutions below but it still dosen't work. My UI is like this:
Text(providerGridPagination.itemgrid[index].price
.toString()),
IconButton(
onPressed: () {
context.read<ProviderGridProduct>().addToCart(
providerGridPagination.itemgrid[index]);
},
icon: iconChage())
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 change the icon just simply do this:
setState(()=> isPressed = !isPressed)
CodePudding user response:
Use state for toggle _isPressed.
Update _isPressed in onPressed function for updating value.
setState(() {
_isPressed = !_isPressed;
});
Update your code in short form like
Widget iconChage(){
return Icon(_isPressed ? Icons.ten_k:Icons.eleven_mp);
}
