my_checkbox_group.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import 'package:flutter/material.dart';
  2. class MyCheckboxGroup extends StatefulWidget {
  3. final List<Map<String, dynamic>> items;
  4. final bool isSingleSelect;
  5. final String nameStr;
  6. final String valueStr;
  7. final ValueChanged<List<Map<String, dynamic>>> onChanged;
  8. final List<Map<String, dynamic>>? defaultSelectedItems;
  9. final TextStyle? labelStyle;
  10. MyCheckboxGroup({
  11. required this.items,
  12. this.isSingleSelect = false,
  13. this.valueStr = 'id',
  14. this.nameStr = 'label',
  15. required this.onChanged,
  16. this.defaultSelectedItems,
  17. this.labelStyle = const TextStyle(
  18. fontSize: 14,
  19. fontWeight: FontWeight.w500,
  20. ),
  21. });
  22. @override
  23. _MyCheckboxGroupState createState() => _MyCheckboxGroupState();
  24. }
  25. class _MyCheckboxGroupState extends State<MyCheckboxGroup> {
  26. Set<String> _selectedItemKeys = {};
  27. @override
  28. void initState() {
  29. super.initState();
  30. if (widget.defaultSelectedItems != null) {
  31. _selectedItemKeys.addAll(widget.defaultSelectedItems!.map((item) => item[widget.valueStr] as String));
  32. widget.onChanged(widget.items.where((item) => _selectedItemKeys.contains(item[widget.valueStr] as String)).toList());
  33. }
  34. }
  35. void _toggleSelection(String key) {
  36. if (widget.isSingleSelect) {
  37. setState(() {
  38. _selectedItemKeys.clear();
  39. _selectedItemKeys.add(key);
  40. });
  41. } else {
  42. setState(() {
  43. if (_selectedItemKeys.contains(key)) {
  44. _selectedItemKeys.remove(key);
  45. } else {
  46. _selectedItemKeys.add(key);
  47. }
  48. });
  49. }
  50. widget.onChanged(widget.items.where((item) => _selectedItemKeys.contains(item[widget.valueStr] as String)).toList());
  51. }
  52. @override
  53. Widget build(BuildContext context) {
  54. return Column(
  55. children: widget.items.map((item) {
  56. final key = item[widget.valueStr] as String;
  57. final label = item[widget.nameStr] as String;
  58. return Container(
  59. child: Row(
  60. children: [
  61. Checkbox(
  62. value: _selectedItemKeys.contains(key),
  63. onChanged: (bool? checked) {
  64. if (checked != null) {
  65. _toggleSelection(key);
  66. }
  67. },
  68. ),
  69. Text(
  70. label,
  71. style: widget.labelStyle ?? const TextStyle(
  72. fontSize: 14,
  73. fontWeight: FontWeight.w500,
  74. ),
  75. ),
  76. ],
  77. ),
  78. );
  79. }).toList(),
  80. );
  81. }
  82. }