我想创建一个选项芯片列表,并在其中选择多个选项。我还想在选择选项时更改颜色。选项是动态的。我尝试使用以下函数,但 onselectionchanged 显示空错误,并且点击时颜色不会改变。请问有什么建议吗??
_buildChoiceList() {
List<Widget> choices = [];
options.forEach((item) {
choices.add(Container(
padding: const EdgeInsets.all(2.0),
child: ChoiceChip(
label: Text(item),
selected: selectedOptions.contains(item),
backgroundColor: Color(0xffff08222),
onSelected: (selected) {
setState(() {
selectedOptions.contains(item)
? selectedOptions.remove(item)
: selectedOptions.add(item);
widget.onSelectionChanged(selectedOptions);
});
},
),
));
});
return choices;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
List<String> hobbyList = [
'Shopping',
'Comedy',
'Brunch',
'Music',
'Road Trips',
'Tea',
'Trivia',
'Comedy',
'Clubbing',
'Drinking',
'Wine',
'Hiking',
'Yoga',
'Volleyball',
'Craft Beer',
'Dogs',
'Cats',
'Activism',
'Vlogging',
'Museum',
'Dancing',
'Running',
'Singing',
'Make-Up',
'Concert',
'Cafe',
'Theater',
'Baking',
'Gardening',
'Cooking',
'Video Games',
'Camping'
];
List<String>? selectedHobby = [];
Wrap(children: hobbyList.map(
(hobby) {
bool isSelected = false;
if (selectedHobby!.contains(hobby)) {
isSelected = true;
}
return GestureDetector(
onTap: () {
if (!selectedHobby!.contains(hobby)) {
if (selectedHobby!.length < 5) {
selectedHobby!.add(hobby);
setState(() {});
print(selectedHobby);
}
} else {
selectedHobby!
.removeWhere((element) => element == hobby);
setState(() {});
print(selectedHobby);
}
},
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 5, vertical: 4),
child: Container(
padding: EdgeInsets.symmetric(
vertical: 5, horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: isSelected
? kActiveColor
: Colors.grey,
width: 2)),
child: Text(
hobby,
style: TextStyle(
color:
isSelected ? kActiveColor : Colors.grey,
fontSize: 14),
),
)),
);
},
).toList(),
),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12030 次 |
| 最近记录: |