watchValue<T extends Object, R> function
- ValueListenable<
R> selectProperty(- T
- bool allowObservableChange = false,
- String? instanceName,
- GetIt? getIt,
- dynamic param1,
- dynamic param2,
watchValue observes a ValueListenable property of an object registered in get_it
and triggers a rebuild whenever it notifies a change and returns its current
value. It's basically a shortcut for watchIt<T>().value
As this is a common scenario it allows us a type safe concise way to do this.
final userName = watchValue<UserManager, String>((user) => user.userName);
is an example of how to use it.
We can use the strength of generics to infer the type of the property and write
it even more expressively like this:
final userName = watchValue((UserManager user) => user.userName);
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.
param1 and param2 are forwarded to get_it and are only valid if T was
registered with registerCachedFactoryParam. If the params change between
builds and get_it returns a different instance, selectProperty is
re-evaluated on the new instance and the widget switches its subscription
to it. This does not require allowObservableChange.
Implementation
R watchValue<T extends Object, R>(
ValueListenable<R> Function(T) selectProperty, {
bool allowObservableChange = false,
String? instanceName,
GetIt? getIt,
dynamic param1,
dynamic param2,
}) {
assert(_activeWatchItState != null,
'watchValue can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');
final getItInstance = getIt ?? di;
_debugCheckRegistration<T>(
getItInstance, 'watchValue', instanceName, param1, param2);
final parentObject = getItInstance<T>(
instanceName: instanceName, param1: param1, param2: param2);
final observedObject = _activeWatchItState!.watchListenable<T, R>(
parentOrListenable: parentObject,
selector: selectProperty,
allowObservableChange: allowObservableChange,
);
// Get the value from the returned observable (selector only called once!)
return (observedObject as ValueListenable<R>).value;
}