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:get/get_utils/src/extensions/widget_extensions.dart'; import 'package:widgets/ext/ex_widget.dart'; import 'package:widgets/my_load_image.dart'; import 'package:widgets/my_text_view.dart'; /** * 条件单选 Radio */ class CustomRadioCheck extends StatefulWidget { final List options; int? selectedPosition; final Function(int index, String text) onOptionSelected; final bool enable; final Color textColor; CustomRadioCheck({ required this.options, required this.onOptionSelected, this.selectedPosition = 0, this.enable = true, // 默认可用 this.textColor = Colors.white, // 默认可用 }); @override _CustomRadioCheckState createState() => _CustomRadioCheckState(); } class _CustomRadioCheckState extends State { String? _selectedOption; @override void initState() { super.initState(); _initializeSelectedOption(); } void _initializeSelectedOption() { if (widget.selectedPosition != null && widget.selectedPosition! >= 0 && widget.selectedPosition! < widget.options.length) { _selectedOption = widget.options[widget.selectedPosition!]; } else { _selectedOption = widget.options.isNotEmpty ? widget.options[0] : null; } } @override void didUpdateWidget(CustomRadioCheck oldWidget) { super.didUpdateWidget(oldWidget); // 如果 selectedPosition 发生变化,重新初始化选中项 if (oldWidget.selectedPosition != widget.selectedPosition) { _initializeSelectedOption(); } } @override Widget build(BuildContext context) { return Wrap( spacing: 8.0, runSpacing: 8.0, children: widget.options.map((option) { return _buildRadioWithIconAndText( path: option == _selectedOption ? Assets.cptAuthLoginRadioChecked : Assets.cptAuthLoginRadioUncheck, text: option, value: option == _selectedOption, onChanged: widget.enable ? (value) { // 只在可用状态下响应点击 setState(() { _selectedOption = option; int selectedIndex = widget.options.indexOf(option); widget.onOptionSelected(selectedIndex, option); }); } : null, // 如果不可用则不设置回调 ); }).toList(), ); } Widget _buildRadioWithIconAndText({ required String path, required String text, required bool value, required Function(bool)? onChanged, // 允许 onChanged 为 null }) { return Row( mainAxisSize: MainAxisSize.min, children: [ MyAssetImage(path, width: 22, height: 22), SizedBox(width: 10), MyTextView( text.tr, textColor: widget.enable ? widget.textColor : ColorConstants.gray, // 根据 enable 改变文本颜色 fontSize: 14, isFontRegular: true, ), ], ).marginOnly(right: 20, bottom: 5).onTap(() { if (onChanged != null) { // 只有在可用状态下才触发 onChanged(true); } }); } }