import 'package:cs_resources/constants/color_constants.dart'; import 'package:cs_resources/generated/assets.dart'; import 'package:flutter/material.dart'; import 'package:get/get_utils/get_utils.dart'; import 'package:shared/utils/log_utils.dart'; import 'package:widgets/ext/ex_widget.dart'; import 'package:widgets/my_load_image.dart'; import 'package:widgets/my_text_view.dart'; class CustomCheckBox extends StatefulWidget { final List options; final Function(List selectedIndexes) onOptionsSelected; // 选中项的索引回调 final List selectedOptions; // 已选中的选项列表 CustomCheckBox({ required this.options, required this.onOptionsSelected, required this.selectedOptions, }); @override _CustomCheckBoxState createState() => _CustomCheckBoxState(); } class _CustomCheckBoxState extends State { late List _selectedOptions; late List _selectedIndexes; @override void initState() { super.initState(); _initializeSelectedOptions(); } void _initializeSelectedOptions() { _selectedOptions = List.from(widget.selectedOptions); _selectedIndexes = widget.options.asMap().entries.where((entry) => _selectedOptions.contains(entry.value)).map((entry) => entry.key).toList(); // 根据选项匹配初始化索引 } @override void didUpdateWidget(CustomCheckBox oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.selectedOptions != widget.selectedOptions) { _initializeSelectedOptions(); } } @override Widget build(BuildContext context) { return Wrap( spacing: 15.0, runSpacing: 15.0, children: widget.options.asMap().entries.map((entry) { int index = entry.key; String option = entry.value; return _buildCheckBoxWithIconAndText( path: _selectedIndexes.contains(index) ? Assets.baseServiceCheckBoxChecked : Assets.baseServiceCheckBoxUncheck, text: option, value: _selectedIndexes.contains(index), onChanged: (isChecked) { setState(() { if (isChecked) { if (!_selectedOptions.contains(option)) { _selectedOptions.add(option); _selectedIndexes.add(index); } } else { _selectedOptions.remove(option); _selectedIndexes.remove(index); } widget.onOptionsSelected(_selectedIndexes); }); }, ); }).toList(), ); } Widget _buildCheckBoxWithIconAndText({ required String path, required String text, required bool value, required Function(bool) onChanged, }) { return Row( mainAxisSize: MainAxisSize.min, children: [ MyAssetImage(path, width: 20.5, height: 20.5), SizedBox(width: 10), MyTextView( text.tr, textColor: ColorConstants.white, fontSize: 14, isFontRegular: true, ), ], ).onTap(() { onChanged(!value); // 点击时切换选中状态 }); } }