watchValue<T extends Object, R> function
- ValueListenable<
R> selectProperty(- T
- bool allowObservableChange = false,
- String? instanceName,
- GetIt? getIt,
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.
Implementation
R watchValue<T extends Object, R>(
ValueListenable<R> Function(T) selectProperty, {
bool allowObservableChange = false,
String? instanceName,
GetIt? getIt,
}) {
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;
final parentObject = getItInstance<T>(instanceName: instanceName);
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;
}