diff --git a/lib/custom_dropdown.dart b/lib/custom_dropdown.dart index 5531a13..104d825 100644 --- a/lib/custom_dropdown.dart +++ b/lib/custom_dropdown.dart @@ -510,6 +510,22 @@ class _CustomDropdownState extends State> { late MultiSelectController selectedItemsNotifier; FormFieldState<(T?, List)>? _formFieldState; + void _selectedItemListener() { + widget.onChanged?.call(selectedItemNotifier.value); + _formFieldState?.didChange((selectedItemNotifier.value, [])); + if (widget.validateOnChange) { + _formFieldState?.validate(); + } + } + + void _selectedItemsListener() { + widget.onListChanged?.call(selectedItemsNotifier.value); + _formFieldState?.didChange((null, selectedItemsNotifier.value)); + if (widget.validateOnChange) { + _formFieldState?.validate(); + } + } + @override void initState() { super.initState(); @@ -520,21 +536,9 @@ class _CustomDropdownState extends State> { selectedItemsNotifier = widget.multiSelectController ?? MultiSelectController(widget.initialItems ?? []); - selectedItemNotifier.addListener(() { - widget.onChanged?.call(selectedItemNotifier.value); - _formFieldState?.didChange((selectedItemNotifier.value, [])); - if (widget.validateOnChange) { - _formFieldState?.validate(); - } - }); - - selectedItemsNotifier.addListener(() { - widget.onListChanged?.call(selectedItemsNotifier.value); - _formFieldState?.didChange((null, selectedItemsNotifier.value)); - if (widget.validateOnChange) { - _formFieldState?.validate(); - } - }); + selectedItemNotifier.addListener(_selectedItemListener); + + selectedItemsNotifier.addListener(_selectedItemsListener); } @override @@ -570,11 +574,16 @@ class _CustomDropdownState extends State> { void dispose() { if (widget.controller == null) { selectedItemNotifier.dispose(); + } else { + selectedItemNotifier.removeListener(_selectedItemListener); } if (widget.multiSelectController == null) { selectedItemsNotifier.dispose(); + } else { + selectedItemsNotifier.removeListener(_selectedItemsListener); } + super.dispose(); }