Skip to content

Commit

Permalink
Feature: ability to use nullable listener in useListenableSelector (#377
Browse files Browse the repository at this point in the history
)
  • Loading branch information
JWo1F authored Aug 29, 2023
1 parent 0a6d65a commit 824ba73
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
12 changes: 6 additions & 6 deletions packages/flutter_hooks/lib/src/listenable_selector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ part of 'hooks.dart';
///
R useListenableSelector<R>(
Listenable listenable,
Listenable? listenable,
R Function() selector,
) {
return use(_ListenableSelectorHook(listenable, selector));
Expand All @@ -34,7 +34,7 @@ R useListenableSelector<R>(
class _ListenableSelectorHook<R> extends Hook<R> {
const _ListenableSelectorHook(this.listenable, this.selector);

final Listenable listenable;
final Listenable? listenable;
final R Function() selector;

@override
Expand All @@ -49,7 +49,7 @@ class _ListenableSelectorHookState<R>
@override
void initHook() {
super.initHook();
hook.listenable.addListener(_listener);
hook.listenable?.addListener(_listener);
}

@override
Expand All @@ -63,8 +63,8 @@ class _ListenableSelectorHookState<R>
}

if (hook.listenable != oldHook.listenable) {
oldHook.listenable.removeListener(_listener);
hook.listenable.addListener(_listener);
oldHook.listenable?.removeListener(_listener);
hook.listenable?.addListener(_listener);
_selectorResult = hook.selector();
}
}
Expand All @@ -83,7 +83,7 @@ class _ListenableSelectorHookState<R>

@override
void dispose() {
hook.listenable.removeListener(_listener);
hook.listenable?.removeListener(_listener);
}

@override
Expand Down
32 changes: 32 additions & 0 deletions packages/flutter_hooks/test/use_listenable_selector_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,38 @@ void main() {
listenable.dispose();
});

testWidgets('null as Listener', (tester) async {
const notFoundValue = -1;
final testListener = ValueNotifier(false);
final listenable = ValueNotifier(777);
var result = 0;

await tester.pumpWidget(
HookBuilder(
builder: (context) {
final shouldUseListener = useListenableSelector(testListener, () {
return testListener.value;
});

final actualListener = shouldUseListener ? listenable : null;

result = useListenableSelector(actualListener, () {
return actualListener?.value ?? notFoundValue;
});

return Container();
},
),
);

expect(result, notFoundValue);
testListener.value = true;

await tester.pump();

expect(result, listenable.value);
});

testWidgets('update selector', (tester) async {
final listenable = ValueNotifier(0);
var isOdd = false;
Expand Down

0 comments on commit 824ba73

Please sign in to comment.