Skip to content

Commit a029daa

Browse files
authored
Wrap routing in FocusScope in WidgetsApp.router (flutter#192601)
In flutter#109702, Navigator's internal `FocusScopeNode` was removed and hoisted into `WidgetsApp`, but only inside the `else if (_usesNavigator)` branch. As a result, apps using `WidgetsApp.router` (including `MaterialApp.router` and `CupertinoApp.router` with `RouterConfig` or `RouterDelegate`) lacked the enclosing `FocusScope(debugLabel: 'Navigator Scope', autofocus: true)`. On Flutter Web with semantics enabled (`ensureSemantics()`), when widgets such as `Autocomplete` show an `OverlayPortal`, the semantics compiler reparents the route node under a newly synthesized container node. Without an enclosing `FocusScope`, moving the route's semantics node detaches it from its previous DOM parent, triggering a native browser blur event on any focused `<input>`. The text field loses focus immediately after typing a single character, causing the options overlay to dismiss. This change wraps `routing` in `FocusScope` whenever `routing != null` in `WidgetsApp`, ensuring consistent focus scope hierarchy across `_usesNavigator`, `_usesRouterWithConfig`, and `_usesRouterWithDelegates`. Fixes flutter#187561 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 5857c36 commit a029daa

2 files changed

Lines changed: 249 additions & 22 deletions

File tree

‎packages/flutter/lib/src/widgets/app.dart‎

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -810,7 +810,8 @@ class WidgetsApp extends StatefulWidget {
810810
/// [Localizations], consider [onGenerateTitle] instead.
811811
///
812812
/// The [builder] callback is passed two arguments, the [BuildContext] (as
813-
/// `context`) and a [Navigator] or [Router] widget (as `child`).
813+
/// `context`) and a [FocusScope] widget enclosing the [Navigator] or [Router]
814+
/// (as `child`).
814815
///
815816
/// If no routes are provided to the regular [WidgetsApp] constructor using
816817
/// [home], [routes], [onGenerateRoute], or [onUnknownRoute], the `child` will
@@ -1691,27 +1692,23 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
16911692
);
16921693
} else if (_usesNavigator) {
16931694
assert(_navigator != null);
1694-
routing = FocusScope(
1695-
debugLabel: 'Navigator Scope',
1696-
autofocus: true,
1697-
child: Navigator(
1698-
clipBehavior: Clip.none,
1699-
restorationScopeId: 'nav',
1700-
key: _navigator,
1701-
initialRoute: _initialRouteName,
1702-
onGenerateRoute: _onGenerateRoute,
1703-
onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null
1704-
? Navigator.defaultGenerateInitialRoutes
1705-
: (NavigatorState navigator, String initialRouteName) {
1706-
return widget.onGenerateInitialRoutes!(initialRouteName);
1707-
},
1708-
onUnknownRoute: _onUnknownRoute,
1709-
observers: widget.navigatorObservers!,
1710-
routeTraversalEdgeBehavior: kIsWeb
1711-
? TraversalEdgeBehavior.leaveFlutterView
1712-
: TraversalEdgeBehavior.parentScope,
1713-
reportsRouteUpdateToEngine: true,
1714-
),
1695+
routing = Navigator(
1696+
clipBehavior: Clip.none,
1697+
restorationScopeId: 'nav',
1698+
key: _navigator,
1699+
initialRoute: _initialRouteName,
1700+
onGenerateRoute: _onGenerateRoute,
1701+
onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null
1702+
? Navigator.defaultGenerateInitialRoutes
1703+
: (NavigatorState navigator, String initialRouteName) {
1704+
return widget.onGenerateInitialRoutes!(initialRouteName);
1705+
},
1706+
onUnknownRoute: _onUnknownRoute,
1707+
observers: widget.navigatorObservers!,
1708+
routeTraversalEdgeBehavior: kIsWeb
1709+
? TraversalEdgeBehavior.leaveFlutterView
1710+
: TraversalEdgeBehavior.parentScope,
1711+
reportsRouteUpdateToEngine: true,
17151712
);
17161713
} else if (_usesRouterWithConfig) {
17171714
routing = Router<Object>.withConfig(
@@ -1720,6 +1717,10 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
17201717
);
17211718
}
17221719

1720+
if (routing != null) {
1721+
routing = FocusScope(debugLabel: 'Navigator Scope', autofocus: true, child: routing);
1722+
}
1723+
17231724
Widget result;
17241725
if (widget.builder != null) {
17251726
result = Builder(

‎packages/flutter/test/widgets/app_test.dart‎

Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// found in the LICENSE file.
44

55
import 'package:flutter/foundation.dart';
6+
import 'package:flutter/semantics.dart';
67
import 'package:flutter/services.dart';
78
import 'package:flutter/widgets.dart';
89
import 'package:flutter_test/flutter_test.dart';
@@ -461,6 +462,231 @@ void main() {
461462
expect(find.text('/'), findsOneWidget);
462463
});
463464

465+
testWidgets('WidgetsApp.router wraps routing in FocusScope', (WidgetTester tester) async {
466+
final delegate = SimpleNavigatorRouterDelegate(
467+
builder: (BuildContext context, RouteInformation information) {
468+
return Text(information.uri.toString());
469+
},
470+
onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) =>
471+
true,
472+
);
473+
addTearDown(delegate.dispose);
474+
await tester.pumpWidget(
475+
WidgetsApp.router(
476+
routeInformationParser: SimpleRouteInformationParser(),
477+
routerDelegate: delegate,
478+
color: const Color(0xFF123456),
479+
),
480+
);
481+
482+
final Finder focusScopeFinder = find.byWidgetPredicate(
483+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
484+
);
485+
expect(focusScopeFinder, findsOneWidget);
486+
487+
final FocusScope focusScope = tester.widget(focusScopeFinder);
488+
expect(focusScope.autofocus, isTrue);
489+
expect(focusScope.child, isA<Router<Object>>());
490+
expect(
491+
delegate.navigatorKey.currentState!.focusNode.enclosingScope?.debugLabel,
492+
'Navigator Scope',
493+
);
494+
});
495+
496+
testWidgets('WidgetsApp.router with routerConfig wraps routing in FocusScope', (
497+
WidgetTester tester,
498+
) async {
499+
final delegate = SimpleNavigatorRouterDelegate(
500+
builder: (BuildContext context, RouteInformation information) {
501+
return Text(information.uri.toString());
502+
},
503+
onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) =>
504+
true,
505+
);
506+
addTearDown(delegate.dispose);
507+
delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
508+
final routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
509+
await tester.pumpWidget(
510+
WidgetsApp.router(routerConfig: routerConfig, color: const Color(0xFF123456)),
511+
);
512+
513+
final Finder focusScopeFinder = find.byWidgetPredicate(
514+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
515+
);
516+
expect(focusScopeFinder, findsOneWidget);
517+
518+
final FocusScope focusScope = tester.widget(focusScopeFinder);
519+
expect(focusScope.autofocus, isTrue);
520+
expect(focusScope.child, isA<Router<Object>>());
521+
expect(
522+
delegate.navigatorKey.currentState!.focusNode.enclosingScope?.debugLabel,
523+
'Navigator Scope',
524+
);
525+
});
526+
527+
testWidgets('WidgetsApp wraps navigator in FocusScope', (WidgetTester tester) async {
528+
final navigatorKey = GlobalKey<NavigatorState>();
529+
await tester.pumpWidget(
530+
WidgetsApp(
531+
navigatorKey: navigatorKey,
532+
color: const Color(0xFF123456),
533+
pageRouteBuilder: <T>(RouteSettings settings, WidgetBuilder builder) {
534+
return PageRouteBuilder<T>(
535+
settings: settings,
536+
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) =>
537+
builder(context),
538+
);
539+
},
540+
home: const Placeholder(),
541+
),
542+
);
543+
544+
final Finder focusScopeFinder = find.byWidgetPredicate(
545+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
546+
);
547+
expect(focusScopeFinder, findsOneWidget);
548+
549+
final FocusScope focusScope = tester.widget(focusScopeFinder);
550+
expect(focusScope.autofocus, isTrue);
551+
expect(focusScope.child, isA<Navigator>());
552+
expect(navigatorKey.currentState!.focusNode.enclosingScope?.debugLabel, 'Navigator Scope');
553+
});
554+
555+
testWidgets('WidgetsApp.router passes FocusScope as child to builder', (
556+
WidgetTester tester,
557+
) async {
558+
final delegate = SimpleNavigatorRouterDelegate(
559+
builder: (BuildContext context, RouteInformation information) {
560+
return Text(information.uri.toString());
561+
},
562+
onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) =>
563+
true,
564+
);
565+
addTearDown(delegate.dispose);
566+
Widget? capturedChild;
567+
await tester.pumpWidget(
568+
WidgetsApp.router(
569+
routeInformationParser: SimpleRouteInformationParser(),
570+
routerDelegate: delegate,
571+
builder: (BuildContext context, Widget? child) {
572+
capturedChild = child;
573+
return child!;
574+
},
575+
color: const Color(0xFF123456),
576+
),
577+
);
578+
579+
expect(capturedChild, isA<FocusScope>());
580+
final focusScope = capturedChild! as FocusScope;
581+
expect(focusScope.debugLabel, 'Navigator Scope');
582+
expect(focusScope.child, isA<Router<Object>>());
583+
});
584+
585+
testWidgets('WidgetsApp.router produces expected semantics tree structure', (
586+
WidgetTester tester,
587+
) async {
588+
final delegate = SimpleNavigatorRouterDelegate(
589+
builder: (BuildContext context, RouteInformation information) {
590+
return const Text('route content', textDirection: TextDirection.ltr);
591+
},
592+
onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) =>
593+
true,
594+
);
595+
addTearDown(delegate.dispose);
596+
597+
await tester.pumpWidget(
598+
WidgetsApp.router(
599+
routeInformationParser: SimpleRouteInformationParser(),
600+
routerDelegate: delegate,
601+
color: const Color(0xFF123456),
602+
),
603+
);
604+
605+
final Finder focusScopeFinder = find.byWidgetPredicate(
606+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
607+
);
608+
final SemanticsNode focusScopeNode = tester.semantics.find(focusScopeFinder);
609+
final SemanticsNode routeContentNode = tester.semantics.find(find.text('route content'));
610+
final SemanticsNode routeScopeNode = routeContentNode.parent!;
611+
612+
// FocusScope's explicitChildNodes prevents WidgetsApp's Directionality from
613+
// merging with the route's semantics node, ensuring the route remains an
614+
// explicit child node even when it is the sole entry in the Navigator.
615+
expect(routeScopeNode, isNot(same(focusScopeNode)));
616+
expect(routeScopeNode.parent, same(focusScopeNode));
617+
618+
// Inserting an overlay entry (such as Autocomplete options or a dialog) does
619+
// not reparent the route's semantics node.
620+
final entry = OverlayEntry(
621+
builder: (BuildContext context) =>
622+
const Text('overlay content', textDirection: TextDirection.ltr),
623+
);
624+
addTearDown(entry.remove);
625+
delegate.navigatorKey.currentState!.overlay!.insert(entry);
626+
await tester.pump();
627+
628+
expect(tester.semantics.find(find.text('route content')).parent, same(routeScopeNode));
629+
expect(routeScopeNode.parent, same(focusScopeNode));
630+
expect(tester.semantics.find(find.text('overlay content')).parent, same(focusScopeNode));
631+
});
632+
633+
testWidgets('WidgetsApp.router with routerConfig produces expected semantics tree structure', (
634+
WidgetTester tester,
635+
) async {
636+
final delegate = SimpleNavigatorRouterDelegate(
637+
builder: (BuildContext context, RouteInformation information) {
638+
return const Text('route content', textDirection: TextDirection.ltr);
639+
},
640+
onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) =>
641+
true,
642+
);
643+
addTearDown(delegate.dispose);
644+
delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
645+
final routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
646+
647+
await tester.pumpWidget(
648+
WidgetsApp.router(routerConfig: routerConfig, color: const Color(0xFF123456)),
649+
);
650+
651+
final Finder focusScopeFinder = find.byWidgetPredicate(
652+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
653+
);
654+
final SemanticsNode focusScopeNode = tester.semantics.find(focusScopeFinder);
655+
final SemanticsNode routeContentNode = tester.semantics.find(find.text('route content'));
656+
final SemanticsNode routeScopeNode = routeContentNode.parent!;
657+
658+
expect(routeScopeNode, isNot(same(focusScopeNode)));
659+
expect(routeScopeNode.parent, same(focusScopeNode));
660+
});
661+
662+
testWidgets('WidgetsApp with navigator produces expected semantics tree structure', (
663+
WidgetTester tester,
664+
) async {
665+
await tester.pumpWidget(
666+
WidgetsApp(
667+
color: const Color(0xFF123456),
668+
pageRouteBuilder: <T>(RouteSettings settings, WidgetBuilder builder) {
669+
return PageRouteBuilder<T>(
670+
settings: settings,
671+
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) =>
672+
builder(context),
673+
);
674+
},
675+
home: const Text('route content', textDirection: TextDirection.ltr),
676+
),
677+
);
678+
679+
final Finder focusScopeFinder = find.byWidgetPredicate(
680+
(Widget widget) => widget is FocusScope && widget.debugLabel == 'Navigator Scope',
681+
);
682+
final SemanticsNode focusScopeNode = tester.semantics.find(focusScopeFinder);
683+
final SemanticsNode routeContentNode = tester.semantics.find(find.text('route content'));
684+
final SemanticsNode routeScopeNode = routeContentNode.parent!;
685+
686+
expect(routeScopeNode, isNot(same(focusScopeNode)));
687+
expect(routeScopeNode.parent, same(focusScopeNode));
688+
});
689+
464690
testWidgets('WidgetsApp has correct default ScrollBehavior', (WidgetTester tester) async {
465691
late BuildContext capturedContext;
466692
await tester.pumpWidget(

0 commit comments

Comments
 (0)