findAssociatedText function

String? findAssociatedText(
  1. Element flutterElement
)

Recursively finds the associated text for a given radio Element.

This function does two things:

  1. It climbs up the widget tree using visitAncestorElements to find a container widget (Row, Column, or Stack) that logically groups the radio with its label.
  2. It performs a depth-first search (DFS) in that container to locate the first Text widget that appears after the radio element.

Returns the Text widget's data if found, otherwise returns null.

Implementation

String? findAssociatedText(Element flutterElement) {
  // Step 1: Traverse upward to find a container widget.
  Element? container;
  flutterElement.visitAncestorElements((Element ancestor) {
    if (ancestor.widget is Row ||
        ancestor.widget is Column ||
        ancestor.widget is Stack) {
      container = ancestor;
      return false; // Stop once we've found a container.
    }
    return true; // Continue searching upward.
  });
  if (container == null) return null; // No suitable grouping container found.

  bool foundRadio = false;
  String? associatedText;

  // Step 2: Depth-first search within the container.
  void dfs(Element element) {
    if (associatedText != null) return; // Already found text, no need to continue.
    if (element == flutterElement) {
      foundRadio = true; // Mark that we've encountered our radio element.
    } else if (foundRadio && element.widget is Text) {
      associatedText = (element.widget as Text).data;
      return;
    }
    element.visitChildElements(dfs);
  }

  container?.visitChildElements(dfs);
  return associatedText;
}