getTopLevelElement function

Element? getTopLevelElement(
  1. Element elem
)

Finds the enclosing top-level element for a given element by climbing the enclosing hierarchy until reaching the library element or null.

Implementation

Element? getTopLevelElement(Element elem) {
  if (elem is LibraryElement) return null;
  Element? current = elem;
  while (current != null) {
    final enclosing = current.enclosingElement;
    if (enclosing == null || enclosing is LibraryElement) {
      return current;
    }
    current = enclosing;
  }
  return null;
}