watchPropertyValue<T extends Listenable, R> function

R watchPropertyValue<T extends Listenable, R>(
  1. R selectProperty(
    1. T
    ), {
  2. T? target,
  3. String? instanceName,
  4. GetIt? getIt,
})

watchPropertyValue allows you to observe a property of a Listenable object and trigger a rebuild whenever the Listenable notifies a change and the value of the property changes and returns the current value of the property. You can achieve a similar result with watchIt<UserManager>().userName but that would trigger a rebuild whenever any property of the UserManager changes. final userName = watchPropertyValue<UserManager, String>((user) => user.userName); could be an example. Or even more expressive and concise: final userName = watchPropertyValue((UserManager user) => user.userName); which lets tha analyzer infer the type of T and R.

If you have a local Listenable and you want to observe only a single property you can pass it as target.

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

R watchPropertyValue<T extends Listenable, R>(
  R Function(T) selectProperty, {
  T? target,
  String? instanceName,
  GetIt? getIt,
}) {
  assert(_activeWatchItState != null,
      'watchPropertyValue can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');
  late final T observedObject;

  final getItInstance = getIt ?? di;
  final parentObject = target ?? getItInstance<T>(instanceName: instanceName);
  final R observedProperty = selectProperty(parentObject);
  assert(
      (observedProperty != null && observedProperty is! Listenable) ||
          (observedProperty == null),
      'selectProperty returns a Listenable. Use watchIt instead');
  observedObject = parentObject;
  _activeWatchItState!.watchPropertyValue<T, R>(
    listenable: observedObject,
    only: selectProperty,
    parentObject: parentObject,
  );
  return observedProperty;
}