Select and deselect List Tile

529 Views Asked by At

I am trying to select multiple list tiles but it is selecting all the list tiles when I only select one. Could someone guide me on this?

Here is my code:

  bool _selected = false;

       body: ListView.builder(
        itemCount: list.length,
        itemBuilder: (_, i) {
          return ListTile(
              tileColor: _selected ? Colors.blue : null,
              title: Text(list[i]['name']),
              onTap: () => setState(() {
                    if (_selected = !_selected) {
                      groupList.add(list[i]);
                      print(groupList);
                      _selected = _selected;
                    } else if (_selected = !_selected) {
                      groupList.remove(list[i]);
                      print(groupList);
                      _selected = !_selected;
                    }
                  }));
        })

Here is the image of the list tile https://i.stack.imgur.com/9EknP.jpg I selected Candice Cook but it selected all the tiles.

1

There are 1 best solutions below

0
On

You should keep record of items that has been selected in a different List or Map so that when you add or remove items from that list you can update the UI accordingly.

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final list = ['Candice Cook', 'David Campbell Cook', 'Marcia Chan'];
  final List<String> _selectedList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
          itemCount: list.length,
          itemBuilder: (_, index) {
            var e = list[index];
            return ListTile(
              selectedTileColor: Colors.purple,
              title: Text(e),
              selected: _selectedList.contains(e),
              onTap: () {
                setState(() {
                  _selectedList.contains(e)
                      ? _selectedList.remove(e)
                      : _selectedList.add(e);
                });
              },
            );
          }),
    );
  }
}