Skip to content

Commit

Permalink
Merge pull request AbdullahChauhan#85 from dufguix/remove-listener-on…
Browse files Browse the repository at this point in the history
…-dispose

remove listener on dispose
  • Loading branch information
AbdullahChauhan authored Sep 26, 2024
2 parents 725950c + bafbd19 commit afb5858
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions lib/custom_dropdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,22 @@ class _CustomDropdownState<T> extends State<CustomDropdown<T>> {
late MultiSelectController<T> selectedItemsNotifier;
FormFieldState<(T?, List<T>)>? _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();
Expand All @@ -520,21 +536,9 @@ class _CustomDropdownState<T> extends State<CustomDropdown<T>> {
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
Expand Down Expand Up @@ -570,11 +574,16 @@ class _CustomDropdownState<T> extends State<CustomDropdown<T>> {
void dispose() {
if (widget.controller == null) {
selectedItemNotifier.dispose();
} else {
selectedItemNotifier.removeListener(_selectedItemListener);
}

if (widget.multiSelectController == null) {
selectedItemsNotifier.dispose();
} else {
selectedItemsNotifier.removeListener(_selectedItemsListener);
}

super.dispose();
}

Expand Down

0 comments on commit afb5858

Please sign in to comment.