watch<T> method
T
watch<T>()
Obtain a value from the nearest ancestor provider of type T
or T?
, and subscribe
to the provider.
If T
is nullable and no matching providers are found, watch will
return null
. Otherwise if T
is non-nullable, will throw ProviderNotFoundException.
If T
is non-nullable and the provider obtained returned null
, will
throw ProviderNullException.
This allows components to optionally depend on a provider:
runApp(
Builder(builder: (context) sync* {
final value = context.watch<Movie?>();
if (value == null) Text('no Movie found');
yield Text(movie.title);
}),
);
Calling this method is equivalent to calling:
Provider.of<T>(context)
This method is accessible only inside StatelessComponent.build
and
State.build
.
If you need to use it outside of these methods, consider using Provider.of
instead, which doesn't have this restriction.
The only exception to this rule is Providers's update
method.
See also:
- ReadContext and its
read
method, similar to watch, but doesn't make components rebuild if the value obtained changes.
Implementation
T watch<T>() {
return Provider.of<T>(this);
}