123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- import 'package:flutter/material.dart';
- class MyCheckboxGroup extends StatefulWidget {
- final List<Map<String, dynamic>> items;
- final bool isSingleSelect;
- final String nameStr;
- final String valueStr;
- final ValueChanged<List<Map<String, dynamic>>> onChanged;
- final List<Map<String, dynamic>>? 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<MyCheckboxGroup> {
- Set<String> _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(),
- );
- }
- }
|