useListener function
void
useListener(
- Listenable? listenable, {
- required bool callInitially,
- required VoidCallback callback,
Adds callback
as listener to listenable
and removes it again upon destruction of the hook.
If called multiple times with different callback
s, the one from the most recent call will be used.
If callInitially
is true, the callback is called immediately, otherwise the callback is called
when the listenable
is notified without triggering a build of the HookWidget
.
Consider this as an alterntive to useListenable
if you want to avoid the HookWidget
to rebuild.
See: useValueListener
Implementation
void useListener(
Listenable? listenable, {
required bool callInitially,
required VoidCallback callback,
}) {
// store the latest version of `callback`
final callbackHolder = useVariable(callback)..value = callback;
useEffect(
() {
if (listenable == null) {
return null;
}
void lcallback() => callbackHolder.value.call();
listenable.addListener(lcallback);
if (callInitially) {
callback();
}
return () => listenable.removeListener(lcallback);
},
[listenable],
);
}