diff --git a/packages/flutter/lib/src/material/search_anchor.dart b/packages/flutter/lib/src/material/search_anchor.dart index c2a5c87244..74ace69e66 100644 --- a/packages/flutter/lib/src/material/search_anchor.dart +++ b/packages/flutter/lib/src/material/search_anchor.dart @@ -357,17 +357,6 @@ class _SearchAnchorState extends State { Navigator.of(context).pop(); } - Rect? getRect(GlobalKey key) { - final BuildContext? context = key.currentContext; - if (context != null) { - final RenderBox searchBarBox = context.findRenderObject()! as RenderBox; - final Size boxSize = searchBarBox.size; - final Offset boxLocation = searchBarBox.localToGlobal(Offset.zero); - return boxLocation & boxSize; - } - return null; - } - bool toggleVisibility() { setState(() { _anchorIsVisible = !_anchorIsVisible; @@ -468,7 +457,8 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { if (context != null) { final RenderBox searchBarBox = context.findRenderObject()! as RenderBox; final Size boxSize = searchBarBox.size; - final Offset boxLocation = searchBarBox.localToGlobal(Offset.zero); + final NavigatorState navigator = Navigator.of(context); + final Offset boxLocation = searchBarBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject()); return boxLocation & boxSize; } return null; diff --git a/packages/flutter/test/material/search_anchor_test.dart b/packages/flutter/test/material/search_anchor_test.dart index 94ab2e616d..b6ff5b02ce 100644 --- a/packages/flutter/test/material/search_anchor_test.dart +++ b/packages/flutter/test/material/search_anchor_test.dart @@ -1679,6 +1679,43 @@ void main() { // No exception. }); + + testWidgets('Docked search should position itself correctly based on closest navigator', (WidgetTester tester) async { + const double rootSpacing = 100.0; + + await tester.pumpWidget(MaterialApp( + builder: (BuildContext context, Widget? child) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(rootSpacing), + child: child, + ), + ); + }, + home: Material( + child: SearchAnchor( + isFullScreen: false, + builder: (BuildContext context, SearchController controller) { + return IconButton( + icon: const Icon(Icons.search), + onPressed: () { + controller.openView(); + }, + ); + }, + suggestionsBuilder: (BuildContext context, SearchController controller) { + return []; + }, + ), + ), + )); + + await tester.tap(find.byIcon(Icons.search)); + await tester.pumpAndSettle(); + + final Rect searchViewRect = tester.getRect(find.descendant(of: findViewContent(), matching: find.byType(SizedBox)).first); + expect(searchViewRect.topLeft, equals(const Offset(rootSpacing, rootSpacing))); + }); } TextStyle? _iconStyle(WidgetTester tester, IconData icon) {