实现此目的的更好方法是创建自定义类
class chipsSelected{
String? title;
bool isSelected;
chipsSelected({this.title,this.isSelected=false});
}
=> 在列表中添加数据
List<chipsSelected> hobbyList = [
chipsSelected(title: 'Shopping',isSelected: false),
chipsSelected(title: 'Brunch',isSelected: false),
chipsSelected(title: 'Music',isSelected: false),
chipsSelected(title: 'Road Trips',isSelected: false),
chipsSelected(title: 'Tea',isSelected: false),
chipsSelected(title: 'Trivia',isSelected: false),
chipsSelected(title: 'Comedy',isSelected: false),
chipsSelected(title: 'Clubbing',isSelected: false),
chipsSelected(title: 'Drinking',isSelected: false),
chipsSelected(title: 'Wine',isSelected: false),
];
List<chipsSelected> selectedHobby = [];
=> 显示
Column(
children: <Widget>[
const SizedBox(height: 16),
Wrap(
children: hobbyList.map(
(hobby) {
var s=hobbyList.where((element) => element.title==hobby.title).first;
return GestureDetector(
onTap: () {
setState(() {
var clickedHobbyList=hobbyList.where((element) => element.title==hobby.title).first;
clickedHobbyList.isSelected=!hobby.isSelected;
});
print("Selected");
print(hobbyList.where((w) => w.isSelected == true).map((w) => w.title.toString()).toList());
print("UnSelected");
print(hobbyList.where((w) => w.isSelected == false).map((w) => w.title.toString()).toList());
},
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 5, vertical: 4),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 5, horizontal: 12),
decoration: BoxDecoration(
color: s.isSelected
? Color(0xFFF5F185)
: Color(0xFFD9D9D9),
borderRadius:
BorderRadius.circular(18),
border: Border.all(
color: s.isSelected
? Color(0xFFF5F185)
: Color(0xFFD9D9D9),
width: 2)),
child: Text(
hobby.title!,
style: TextStyle(
color: s.isSelected
? Colors.black
: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w600),
),
),
),
);
},
).toList(),
),
TextButton(onPressed: (){
print(hobbyList.where((element) => false));
}, child: Text("hhhhh"))
],
),