123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- 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<String> options;
- final Function(List<int> selectedIndexes) onOptionsSelected; // 选中项的索引回调
- final List<String> selectedOptions; // 已选中的选项列表
- CustomCheckBox({
- required this.options,
- required this.onOptionsSelected,
- required this.selectedOptions,
- });
- @override
- _CustomCheckBoxState createState() => _CustomCheckBoxState();
- }
- class _CustomCheckBoxState extends State<CustomCheckBox> {
- late List<String> _selectedOptions;
- late List<int> _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: <Widget>[
- MyAssetImage(path, width: 20.5, height: 20.5),
- SizedBox(width: 10),
- MyTextView(
- text.tr,
- textColor: ColorConstants.white,
- fontSize: 14,
- isFontRegular: true,
- ),
- ],
- ).onTap(() {
- onChanged(!value); // 点击时切换选中状态
- });
- }
- }
|