I'm trying to change the icon when tap on it, but it is not working. I'm trying to implement the Wishlist scenario on it.
My code first is display the favorite_outline
and when I tap on it value of productsList[index].isFav
changes to true
but not displaying favorite
icon.
here is my code.
Widget build(BuildContext context) {
List<ProductsList> productsList = ProductsList.getProducts();
return SafeArea(
child: Scaffold(
appBar: AppBar(),
body: Container(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: productsList.length,
itemBuilder: (BuildContext context, int index) =>
Container(child:
productsList[index].isFav
? IconButton(
onPressed: () {
setState(() {
productsList[index].isFav = false;
});
},
icon: Icon(Icons.favorite))
: IconButton(
onPressed: () {
setState(() {
productsList[index].isFav = true;
});
print(productsList[index].isFav);
},
icon: Icon(Icons.favorite_outline))),
))));
}
here is the ProductList class
class ProductsList {
int id;
String productName;
bool isFav;
ProductsList(
{required this.id,
required this.productName,
,required this.isFav});
static List<ProductsList> getProducts() {
return <ProductsList>[
ProductsList(
id: 1,
productName: "Samsung Microwave",
isFav: false
),
ProductsList(
id: 2,
productName: "Dji Drones",
isFav: false
),
];
}
}
please help how to fix this issue.
CodePudding user response:
When you call setState
, your build
widget rebuild and
List<ProductsList> productsList = ProductsList.getProducts();
call again and your product
list, set again as default:
ProductsList(id: 1, productName: "Samsung Microwave", isFav: false),
ProductsList(id: 2, productName: "Dji Drones", isFav: false),
You should use ChangeNotifier
and notifyListeners()
CodePudding user response:
Try this:-
Widget build(BuildContext context) {
List<ProductsList> productsList = ProductsList.getProducts();
return SafeArea(
child: Scaffold(
appBar: AppBar(),
body: Container(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: productsList.length,
itemBuilder: (BuildContext context, int index) =>
Container(child:
productsList[index].isFav
? IconButton(
onPressed: () {
if(productsList[index].isFav){
setState(() {
productsList[index].isFav = false;
});
}else{
setState(() {
productsList[index].isFav = true;
});
}},
icon:productsList[index].isFav? Icon(Icons.favorite):Icon(Icons.favorite_outline))
),
))));
}