getContext method

BuildContext? getContext(
  1. String id
)

Returns the BuildContext of the mounted widget, or null if not on screen.

The context only exists while the widget is mounted in the tree. If the widget was scrolled out of the viewport but is still mounted, the context exists but the widget may not be visible.

Triple strategy:

  1. Internal GlobalKey (original flow with getGlobalKey)
  2. Element-tree walk searching for McpMetadataKey with that id (direct flow)
  3. Element-tree walk searching for ValueKey<String> with matching value

Implementation

BuildContext? getContext(String id) {
  // Strategy 1: Internal GlobalKey
  final ctx = _widgets[id]?.globalKey.currentContext;
  if (ctx != null) return ctx;

  // Strategy 2 & 3: walk the tree searching for matching key
  BuildContext? found;
  void visit(Element el) {
    if (found != null) return;
    final key = el.widget.key;
    if (key is McpMetadataKey && key.id == id) {
      found = el;
      return;
    }
    if (key is ValueKey<String> && key.value == id) {
      found = el;
      return;
    }
    el.visitChildElements(visit);
  }

  WidgetsBinding.instance.rootElement?.visitChildElements(visit);
  return found;
}