modalRouteForElement function
Returns the nearest route scope for element without registering an
inherited-widget dependency. null means the element is outside a route.
Implementation
ModalRoute<dynamic>? modalRouteForElement(Element element) {
ModalRoute<dynamic>? found;
element.visitAncestorElements((ancestor) {
final widget = ancestor.widget;
// `_ModalScopeStatus` is private to flutter/widgets; match by runtime type.
if (widget.runtimeType.toString() != '_ModalScopeStatus') return true;
try {
final route = (widget as dynamic).route;
if (route is ModalRoute) {
found ??= route;
}
} catch (_) {
// Keep default — treat as current if the private shape changed.
}
return true;
});
return found;
}