Search code examples
flutterdartlistviewbuttonbuilder

Flutter: Change the background color of selected button in ListView.builder


I have a list of items and default color.

List<String> items = ['A', 'B', 'C'];
Color _color = Colors.transparent;

From my code, it changes all the background colors of the buttons.

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {

    return ElevatedButton(
      style: ButtonStyle(backgroundColor: MaterialStateProperty.all(_color)),
      onPressed: () {
        setState(() {
          _color = Colors.blue;
        });
      },
      child: Text(items[index]),
    );

  },
);

So, I want only the selected button to change the background color.


Solution

  • Please try with this

    List<String> items = ['A', 'B', 'C'];
    List<Color> _color = [Colors.transparent,Colors.transparent,Colors.transparent ];
    
    ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              return ElevatedButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(_color[index])),
                onPressed: () {
                  setState(() {
                    if (_color[index] == Colors.blue) {
                      _color[index] = Colors.transparent;
                    } else {
                      _color[index] = Colors.blue;
                    }
                  });
                },
                child: Text(items[index]),
              );
            },
          );
    

    Output:

    enter image description here