点击选中选中多个
如果要实现在一个list中选中多个,可以参考下面的代码。
Set<int> selectedItems = Set<int>();
@override
void initState() {
super.initState();
//从外部传来
selectedItems = widget.selectedItems ?? Set<int>();
}
///生成数据
ListView.builder(
physics: BouncingScrollPhysics(), // 添加physics属性
itemCount: widget.rightItems.length,
itemBuilder: (context, index) {
final item = widget.rightItems[index];
bool isSelected = selectedItems.contains(index); // 判断当前项是否被选中
return GestureDetector(
onTap: () {
// Navigator.pop(context, item);
if (isSelected) {
selectedItems.remove(index);
} else {
selectedItems.add(index);
}
setState(() {});
print(selectedItems);
},
child: Container(
width: 128.0,
height: 37.0,
margin: EdgeInsets.only(bottom: 1.0),
decoration: BoxDecoration(
//样式自定义....
),
child: Center(
child: Text(
///判断item字符长度 太长可省略
item.length > 15 ? '${item.substring(0, 15)}...' : item,
style: TextStyle(
color: isSelected ? Colors.white : Colors.black,
fontSize: 14.0,
),
),
),
),
);
},
);