Here is my code.
bool isAddedToCart = false;
return ListView.builder(
........
ElevatedButton (
child: isAddedToCart? Text('Added to cart') : Text('Add to cart'),
style: ElevatedButton.styleFrom(
primary: Constants.primaryColor,
onPrimary: Constants.appColor
),
onPressed: () async{
setState(() {
isAddedToCart = !isAddedToCart;
});
},
),
The problem is, if I click on that elevated Button the text of that button has to change on that index only. But it is changing in all the index which are in listview.builder.
Can any one have a solution for this that only one button on selected index has to update with changed name.
>Solution :
You need to keep the flag isAddedToCart for each index. You can achieve it by using a Map. Something like this:
// class variable scope.
Map<int, bool> isAddedToCartMap = {};
then use it in your widget:
ElevatedButton (
// if isAddedToCartMap[index] not found, use false as default value.
child: isAddedToCartMap[index]??false ? Text('Added to cart') : Text('Add to cart'),
style: ElevatedButton.styleFrom(
primary: Constants.primaryColor,
onPrimary: Constants.appColor
),
onPressed: () async{
setState(() {
isAddedToCartMap[index] = !isAddedToCartMap[index]??false;
});
},
),