custom_radio_check.dart 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import 'package:cs_resources/constants/color_constants.dart';
  2. import 'package:cs_resources/generated/assets.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:get/get_utils/get_utils.dart';
  5. import 'package:get/get_utils/src/extensions/widget_extensions.dart';
  6. import 'package:widgets/ext/ex_widget.dart';
  7. import 'package:widgets/my_load_image.dart';
  8. import 'package:widgets/my_text_view.dart';
  9. class CustomRadioCheck extends StatefulWidget {
  10. final List<String> options;
  11. int? selectedPosition;
  12. final Function(int index, String text) onOptionSelected;
  13. CustomRadioCheck({
  14. required this.options,
  15. required this.onOptionSelected,
  16. this.selectedPosition = 0,
  17. });
  18. @override
  19. _CustomRadioCheckState createState() => _CustomRadioCheckState();
  20. }
  21. class _CustomRadioCheckState extends State<CustomRadioCheck> {
  22. String? _selectedOption;
  23. @override
  24. void initState() {
  25. super.initState();
  26. // 初始化 _selectedOption
  27. if (widget.selectedPosition != null && widget.selectedPosition! >= 0 && widget.selectedPosition! < widget.options.length) {
  28. _selectedOption = widget.options[widget.selectedPosition!];
  29. } else {
  30. // 默认选择第一个选项,如果 selectedPosition 不在有效范围内
  31. _selectedOption = widget.options.isNotEmpty ? widget.options[0] : null;
  32. }
  33. }
  34. @override
  35. Widget build(BuildContext context) {
  36. return Wrap(
  37. spacing: 8.0, // 水平间距
  38. runSpacing: 8.0, // 垂直间距
  39. children: widget.options.map((option) {
  40. return _buildRadioWithIconAndText(
  41. path: option == _selectedOption ? Assets.cptAuthLoginRadioChecked : Assets.cptAuthLoginRadioUncheck,
  42. text: option,
  43. value: option == _selectedOption,
  44. onChanged: (value) {
  45. setState(() {
  46. _selectedOption = option;
  47. int selectedIndex = widget.options.indexOf(option);
  48. widget.onOptionSelected(selectedIndex, option);
  49. });
  50. },
  51. );
  52. }).toList(),
  53. );
  54. }
  55. Widget _buildRadioWithIconAndText({
  56. required String path,
  57. required String text,
  58. required bool value,
  59. required Function(bool) onChanged,
  60. }) {
  61. return Row(
  62. mainAxisSize: MainAxisSize.min,
  63. children: <Widget>[
  64. MyAssetImage(path, width: 22, height: 22),
  65. SizedBox(width: 10),
  66. MyTextView(
  67. text.tr,
  68. textColor: ColorConstants.white,
  69. fontSize: 14,
  70. isFontRegular: true,
  71. ),
  72. ],
  73. ).marginOnly(right: 20, bottom: 5).onTap(() {
  74. onChanged(true);
  75. });
  76. }
  77. }