listenSignal<T> function

  1. @Deprecated('use SignalsMixin in StatefulWidget')
void listenSignal<T>(
  1. BuildContext context,
  2. ReadonlySignal<T> signal,
  3. void callback(), {
  4. String? debugLabel,
})

Used to listen for updates on a signal but not rebuild the nearest element

final counter = signal(0);
...
@override
Widget build(BuildContext context) {
  listenSignal(context, counter, () {
    if (counter.value == 10) {
      final messenger = ScaffoldMessenger.of(context);
      messenger.hideCurrentSnackBar();
      messenger.showSnackBar(
        const SnackBar(content: Text('You hit 10 clicks!')),
      );
    }
  });
...
}

Implementation

@Deprecated('use SignalsMixin in StatefulWidget')
void listenSignal<T>(
  BuildContext context,
  ReadonlySignal<T> signal,
  void Function() callback, {
  String? debugLabel,
}) {
  final ctx = context;
  if (ctx is StatefulElement) {
    final state = ctx.state;
    if (state is SignalsMixin) {
      state.listenSignal(signal, callback, debugLabel: debugLabel);
      return;
    }
  }
  if (ctx is Element) {
    final key = ctx.hashCode;
    if (_elementRefs[key] == null) {
      final label = [
        'widget',
        ctx.widget.runtimeType.toString(),
        ctx.widget.hashCode.toString(),
      ].join('=');
      final watcher = ElementWatcher(key, label, WeakReference(ctx));
      _elementRefs[key] = watcher;
      _removeSignalWatchers();
    }
    _elementRefs[key]?.listen(signal, callback);
  }
}