useWidgetRef<T extends SetupWidget> function

WidgetRef<T> useWidgetRef<T extends SetupWidget>()

Creates a reference to a SetupWidget of type T.

This function creates a WidgetRef that provides access to the closest ancestor widget of type T in the widget tree. If no such widget exists, the reference will contain null.

The reference is automatically registered with the current element if the element's widget matches type T.

Returns a WidgetRef<T> that can be used to access the referenced widget and its build context.

Implementation

WidgetRef<T> useWidgetRef<T extends SetupWidget>() {
  final elementRef = switch (currentElement) {
    SetupElementImpl element when element.widget is T => ref(element),
    _ => ref<SetupElementImpl?>(null),
  };

  final widgetRef = WidgetReferenceImpl<T>(elementRef);
  if (currentElement != null && currentElement?.widget is T) {
    currentElement!.widgetRefs.add(widgetRef);
  }

  return widgetRef;
}