watch<T extends Object> method

T watch<T extends Object>({
  1. T orElse()?,
})

Obtain a value from the nearest ancestor scope of type T and subscribe to the scope.

If no matching scopes are found, watch will searches in GlobalScope.read

Throw ScopeNotFoundException if T does not exist.

Calling this method is equivalent to calling:

Scope.of<T>(context, listen: true)

This method is accessible only inside StatelessWidget.build, State.build, and State.didChangeDependencies.
If you need to use it outside of these methods, consider using Scope.of instead, which doesn't have this restriction.\

See also:

  • read method, similar to watch, but doesn't make widgets rebuild if the value obtained changes.

Implementation

T watch<T extends Object>({final T Function()? orElse}) {
  final value = Scope.maybeOf<T>(this, listen: true);
  if (value != null) {
    return value;
  } else if (orElse != null) {
    return orElse();
  }
  throw ScopeNotFoundException(T);
}