of<T> static method

T of<T>(
  1. BuildContext context, {
  2. bool rebuild = false,
})

Retrieves the dependency of type T from the nearest ancestor Binder widget.

This method looks up the widget tree for a Binder widget of the specified type and returns its controller. It's the primary way to access dependencies from the widget tree.

Parameters:

  • context: The build context to search from
  • rebuild: If true, the widget will rebuild when the controller changes

Returns the controller of type T.

Throws a BindError if no matching Binder is found in the widget tree.

Implementation

static T of<T>(
  BuildContext context, {
  bool rebuild = false,
}) {
  // Get the element for the nearest Binder of type T
  final element = context.getElementForInheritedWidgetOfExactType<Binder<T>>()
      as BindElement<T>?;

  // Use pattern matching to handle the result
  return switch (element) {
    // If no element is found, throw a descriptive error
    null => throw BindError<String>(
        controller: "No Binder for type $T found in the widget tree",
      ),

    // If element is found, optionally register for rebuilds and return the controller
    var found => () {
        // If rebuild is requested, register for dependency notifications
        if (rebuild) {
          context.dependOnInheritedElement(found);
        }
        return found.controller;
      }()
  };
}