import 'package:flutter/material.dart'; class MyCheckboxGroup extends StatefulWidget { final List> items; final bool isSingleSelect; final String nameStr; final String valueStr; final ValueChanged>> onChanged; final List>? defaultSelectedItems; final TextStyle? labelStyle; MyCheckboxGroup({ required this.items, this.isSingleSelect = false, this.valueStr = 'id', this.nameStr = 'label', required this.onChanged, this.defaultSelectedItems, this.labelStyle = const TextStyle( fontSize: 14, fontWeight: FontWeight.w500, ), }); @override _MyCheckboxGroupState createState() => _MyCheckboxGroupState(); } class _MyCheckboxGroupState extends State { Set _selectedItemKeys = {}; @override void initState() { super.initState(); if (widget.defaultSelectedItems != null) { _selectedItemKeys.addAll(widget.defaultSelectedItems!.map((item) => item[widget.valueStr] as String)); widget.onChanged(widget.items.where((item) => _selectedItemKeys.contains(item[widget.valueStr] as String)).toList()); } } void _toggleSelection(String key) { if (widget.isSingleSelect) { setState(() { _selectedItemKeys.clear(); _selectedItemKeys.add(key); }); } else { setState(() { if (_selectedItemKeys.contains(key)) { _selectedItemKeys.remove(key); } else { _selectedItemKeys.add(key); } }); } widget.onChanged(widget.items.where((item) => _selectedItemKeys.contains(item[widget.valueStr] as String)).toList()); } @override Widget build(BuildContext context) { return Column( children: widget.items.map((item) { final key = item[widget.valueStr] as String; final label = item[widget.nameStr] as String; return Container( child: Row( children: [ Checkbox( value: _selectedItemKeys.contains(key), onChanged: (bool? checked) { if (checked != null) { _toggleSelection(key); } }, ), Text( label, style: widget.labelStyle ?? const TextStyle( fontSize: 14, fontWeight: FontWeight.w500, ), ), ], ), ); }).toList(), ); } }