import 'package:cs_resources/constants/color_constants.dart'; import 'package:cs_resources/generated/assets.dart'; import 'package:flutter/material.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; // 已选中的选项列表 final Color textColor; CustomCheckBox({ required this.options, required this.onOptionsSelected, required this.selectedOptions, this.textColor = Colors.white, // 默认可用 }); @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); Log.d("oldWidget - selectedOptions :${oldWidget.selectedOptions} newWidget - selectedOptions:${widget.selectedOptions} "); // 使用ListEquality来比较两个列表的内容 if (!_listEquals(oldWidget.selectedOptions, widget.selectedOptions)) { _initializeSelectedOptions(); } } bool _listEquals(List list1, List list2) { if (list1.length != list2.length) { return false; } for (int i = 0; i < list1.length; i++) { if (list1[i] != list2[i]) { return false; } } return true; } @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: 15.5, height: 15.5), const SizedBox(width: 10), MyTextView( text, textColor: widget.textColor, fontSize: 14, isFontRegular: true, ), ], ).onTap(() { onChanged(!value); // 点击时切换选中状态 }); } }