123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import 'package:cs_resources/constants/color_constants.dart';
- import 'package:cs_resources/generated/assets.dart';
- import 'package:flutter/material.dart';
- import 'package:widgets/my_load_image.dart';
- import 'package:widgets/my_text_view.dart';
- import '../ext/ex_widget.dart';
- /*
- * 条件单选 Radio
- */
- class CustomRadioCheck extends StatefulWidget {
- final List<String> 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<CustomRadioCheck> {
- 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.baseServiceRadioChecked : Assets.baseServiceRadioUncheck,
- 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: <Widget>[
- MyAssetImage(path, width: 25, height: 25),
- const SizedBox(width: 10),
- MyTextView(
- text,
- textColor: widget.enable ? widget.textColor : ColorConstants.gray, // 根据 enable 改变文本颜色
- fontSize: 14,
- isFontRegular: true,
- ),
- ],
- ).marginOnly(right: 20, bottom: 5).onTap(() {
- if (onChanged != null) {
- // 只有在可用状态下才触发
- onChanged(true);
- }
- });
- }
- }
|