BuildContext.watch is a method similar to BuildContext.use, but with an added functionality.
It not only retrieves the T dependency but also registers the current widget as a listener for any changes to the states set or otherwise any changes in the T dependency.
Consequently, whenever changes, the widget using BuildContext.watch is automatically notified and rebuilt.
Syntax & description
context: The BuildContext object, which provides information about the current widget in the tree.
T: The type of the dependency you want to access.
These are some points to consider:
If the type is nullable, the method will return null if the dependency is not found.
If the type is not nullable, the method will throw an exception if the dependency is not found.
listenStates: An optional function that returns a list of state(RtState) to listen for changes. If omitted, the method will listen for any changes in the T dependency.
id: An optional identifier for the T dependency. If omitted, the dependency will be located by its type(T).
Usage
This following example demonstrates how to use BuildContext.watch:
counter.dart
counter_view.dart
counter_controller.dart
main.dart
In this example, we use BuildContext.watch to get the instance of CounterController from the nearest ancestor provider(located in main.dart) and listen for changes in the count state.