flutter 选择和取消选择列表平铺

qgelzfjb  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(143)

我试图选择多个列表块,但当我只选择一个列表块时,它却选择了所有列表块。有人能指导我吗?
下面是我的代码:

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;
                    }
                  }));
        })

这是列表图块https://imgur.com/a/T6kxLyT的图像,我选择了Candice Cook,但它选择了所有图块。

xqk2d5yq

xqk2d5yq1#

您应该记录在其他ListMap中选择的item,以便在该列表中添加或删除项目时可以相应地更新UI。

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

相关问题