addStrongRefListener method
Register a closure to be called when the object notifies its listeners.
The strongRefListener
MUST be held by a strong reference by the object
that adds it. If the listener is an anonymous function or a reference to a
function that goes out of scope, it will be garbage collected and
automatically removed without notice.
This method must not be called after dispose has been called.
Example of Correct Usage:
class MyWidgetState extends State<MyWidget> {
// Assign the listener to a field to maintain a strong reference.
late final VoidCallback _myListener = () => print('Notified!');
@override
void initState() {
super.initState();
myNotifier.addStrongRefListener(strongRefListener: _myListener);
}
@override
void dispose() {
myNotifier.removeListener(_myListener);
super.dispose();
}
}
Implementation
void addStrongRefListener({
@mustBeStrongRefOrError required VoidCallback strongRefListener,
}) {
assert(!_isDisposed, 'A $runtimeType was used after being disposed.');
// Per the Listenable contract, addListener should be callable with the same
// listener multiple times. We do not de-duplicate.
if (_count == _listeners.length) {
_growListenersList();
}
_listeners[_count++] = WeakReference(strongRefListener);
_attachFinalizer(strongRefListener);
}