registerHandler<T extends Object, R> function

void registerHandler<T extends Object, R>({
  1. ValueListenable<R> select(
    1. T
    )?,
  2. required void handler(
    1. BuildContext context,
    2. R newValue,
    3. void cancel()
    ),
  3. T? target,
  4. bool allowObservableChange = false,
  5. bool executeImmediately = false,
  6. String? instanceName,
  7. GetIt? getIt,
})

registerHandler registers a handler function for a ValueListenable exactly once on the first build and unregister it when the widget is destroyed. select allows you to register the handler to a member of the of the Object stored in GetIt. If you set executeImmediately to true the handler will be called immediately with the current value of the ValueListenable and not on the first change notification. All handler functions get passed in a cancel function that allows to kill the registration from inside the handler. If you want to register a handler to a Listenable that is not registered in get_it you can pass it as target. if you pass null as select, T or target has to be a Listenable or ValueListenable.

allowObservableChange determines whether the observable can change between builds. When false (default), the selector is only called once on the first build, and any observable change will throw an exception. This is optimal for static observables and prevents memory leaks from inline chain creation. Set to true when you need to switch between different observables based on build-time state.

instanceName is the optional name of the instance if you registered it with a name in get_it.

getIt is the optional instance of get_it to use if you don't want to use the default one. 99% of the time you won't need this.

Implementation

void registerHandler<T extends Object, R>({
  ValueListenable<R> Function(T)? select,
  required void Function(
          BuildContext context, R newValue, void Function() cancel)
      handler,
  T? target,
  bool allowObservableChange = false,
  bool executeImmediately = false,
  String? instanceName,
  GetIt? getIt,
}) {
  assert(_activeWatchItState != null,
      'registerHandler can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');

  final getItInstance = getIt ?? di;
  final parentObject = target ?? getItInstance<T>(instanceName: instanceName);

  // Validate target type when no select function is provided
  if (select == null && parentObject is! Listenable) {
    throw ArgumentError(
        'When no select function is provided, target must be a Listenable. '
        'Got: ${parentObject.runtimeType}');
  }

  _activeWatchItState!.watchListenable<T, R>(
    parentOrListenable: parentObject,
    selector: select,
    allowObservableChange: allowObservableChange,
    handler: handler,
    executeImmediately: executeImmediately,
  );
}