Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Update Elevated Button title on Pressed in Particular index of ListView.builder

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
       });
       
     },
  
   ),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading