diff --git a/packages/flutter/lib/src/widgets/focus_traversal.dart b/packages/flutter/lib/src/widgets/focus_traversal.dart index 068c968c18..09a6fcb25b 100644 --- a/packages/flutter/lib/src/widgets/focus_traversal.dart +++ b/packages/flutter/lib/src/widgets/focus_traversal.dart @@ -314,7 +314,6 @@ abstract class FocusTraversalPolicy with Diagnosticable { } // Sort the member lists using the individual policy sorts. - final Set groupKeys = groups.keys.toSet(); for (final FocusNode? key in groups.keys) { final List sortedMembers = groups[key]!.policy.sortDescendants(groups[key]!.members, currentNode).toList(); groups[key]!.members.clear(); @@ -326,7 +325,7 @@ abstract class FocusTraversalPolicy with Diagnosticable { final List sortedDescendants = []; void visitGroups(_FocusTraversalGroupInfo info) { for (final FocusNode node in info.members) { - if (groupKeys.contains(node)) { + if (groups.containsKey(node)) { // This is a policy group focus node. Replace it with the members of // the corresponding policy group. visitGroups(groups[node]!); @@ -336,8 +335,10 @@ abstract class FocusTraversalPolicy with Diagnosticable { } } - // Visit the children of the scope. - visitGroups(groups[scopeGroupMarker?.focusNode]!); + // Visit the children of the scope, if any. + if (groups.isNotEmpty && groups.containsKey(scopeGroupMarker?.focusNode)) { + visitGroups(groups[scopeGroupMarker?.focusNode]!); + } // Remove the FocusTraversalGroup nodes themselves, which aren't focusable. // They were left in above because they were needed to find their members diff --git a/packages/flutter/test/widgets/focus_traversal_test.dart b/packages/flutter/test/widgets/focus_traversal_test.dart index cba05dbd41..d514039575 100644 --- a/packages/flutter/test/widgets/focus_traversal_test.dart +++ b/packages/flutter/test/widgets/focus_traversal_test.dart @@ -2015,6 +2015,14 @@ void main() { expect(events.length, 2); }); + testWidgets('Focus traversal does not throw when no focusable is available in a group', (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Scaffold(body: ListTile(title: Text('title'))))); + final FocusNode? initialFocus = primaryFocus; + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + expect(primaryFocus, equals(initialFocus)); + }); + testWidgets('Focus traversal does not break when no focusable is available on a WidgetsApp', (WidgetTester tester) async { final List events = [];