diff --git a/packages/flutter/lib/src/material/autocomplete.dart b/packages/flutter/lib/src/material/autocomplete.dart index d917393cd4..32d8bae65a 100644 --- a/packages/flutter/lib/src/material/autocomplete.dart +++ b/packages/flutter/lib/src/material/autocomplete.dart @@ -180,55 +180,114 @@ class _AutocompleteOptions extends StatelessWidget { }); final AutocompleteOptionToString displayStringForOption; - final AutocompleteOnSelected onSelected; final OptionsViewOpenDirection openDirection; - final Iterable options; final double optionsMaxHeight; @override Widget build(BuildContext context) { + final int highlightedIndex = AutocompleteHighlightedOption.of(context); + final AlignmentDirectional optionsAlignment = switch (openDirection) { OptionsViewOpenDirection.up => AlignmentDirectional.bottomStart, OptionsViewOpenDirection.down => AlignmentDirectional.topStart, }; + return Align( alignment: optionsAlignment, child: Material( elevation: 4.0, child: ConstrainedBox( constraints: BoxConstraints(maxHeight: optionsMaxHeight), - child: ListView.builder( - padding: EdgeInsets.zero, - shrinkWrap: true, - itemCount: options.length, - itemBuilder: (BuildContext context, int index) { - final T option = options.elementAt(index); - return InkWell( - onTap: () { - onSelected(option); - }, - child: Builder( - builder: (BuildContext context) { - final bool highlight = AutocompleteHighlightedOption.of(context) == index; - if (highlight) { - SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { - Scrollable.ensureVisible(context, alignment: 0.5); - }, debugLabel: 'AutocompleteOptions.ensureVisible'); - } - return Container( - color: highlight ? Theme.of(context).focusColor : null, - padding: const EdgeInsets.all(16.0), - child: Text(displayStringForOption(option)), - ); - }, - ), - ); - }, + child: _AutocompleteOptionsList( + displayStringForOption: displayStringForOption, + highlightedIndex: highlightedIndex, + onSelected: onSelected, + options: options, ), ), ), ); } } + +class _AutocompleteOptionsList extends StatefulWidget { + const _AutocompleteOptionsList({ + required this.displayStringForOption, + required this.highlightedIndex, + required this.onSelected, + required this.options, + }); + + final AutocompleteOptionToString displayStringForOption; + final int highlightedIndex; + final AutocompleteOnSelected onSelected; + final Iterable options; + + @override + State<_AutocompleteOptionsList> createState() => _AutocompleteOptionsListState(); +} + +class _AutocompleteOptionsListState extends State<_AutocompleteOptionsList> { + final ScrollController _scrollController = ScrollController(); + + @override + void didUpdateWidget(_AutocompleteOptionsList oldWidget) { + super.didUpdateWidget(oldWidget); + + if (widget.highlightedIndex != oldWidget.highlightedIndex) { + SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { + if (!mounted) { + return; + } + final BuildContext? highlightedContext = + GlobalObjectKey(widget.options.elementAt(widget.highlightedIndex)).currentContext; + if (highlightedContext == null) { + _scrollController.jumpTo( + widget.highlightedIndex == 0 ? 0.0 : _scrollController.position.maxScrollExtent, + ); + } else { + Scrollable.ensureVisible(highlightedContext, alignment: 0.5); + } + }, debugLabel: 'AutocompleteOptions.ensureVisible'); + } + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final int highlightedIndex = AutocompleteHighlightedOption.of(context); + + return ListView.builder( + padding: EdgeInsets.zero, + shrinkWrap: true, + controller: _scrollController, + itemCount: widget.options.length, + itemBuilder: (BuildContext context, int index) { + final T option = widget.options.elementAt(index); + return InkWell( + key: GlobalObjectKey(option), + onTap: () { + widget.onSelected(option); + }, + child: Builder( + builder: (BuildContext context) { + final bool highlight = highlightedIndex == index; + return Container( + color: highlight ? Theme.of(context).focusColor : null, + padding: const EdgeInsets.all(16.0), + child: Text(widget.displayStringForOption(option)), + ); + }, + ), + ); + }, + ); + } +} diff --git a/packages/flutter/lib/src/widgets/autocomplete.dart b/packages/flutter/lib/src/widgets/autocomplete.dart index 958ce9e4ae..08363b247c 100644 --- a/packages/flutter/lib/src/widgets/autocomplete.dart +++ b/packages/flutter/lib/src/widgets/autocomplete.dart @@ -8,6 +8,7 @@ library; import 'dart:async'; import 'dart:math' show max, min; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; @@ -321,6 +322,10 @@ class _RawAutocompleteState extends State> debugLabel: '_RawAutocompleteState', ); + // The number of options to scroll by "page", such as when using the page + // up/down keys. + static const int _pageSize = 4; + TextEditingController? _internalTextEditingController; TextEditingController get _textEditingController { return widget.textEditingController ?? @@ -342,6 +347,23 @@ class _RawAutocompleteState extends State> onInvoke: _highlightNextOption, isEnabledCallback: () => _canShowOptionsView, ), + AutocompleteFirstOptionIntent: _AutocompleteCallbackAction( + onInvoke: _highlightFirstOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteLastOptionIntent: _AutocompleteCallbackAction( + onInvoke: _highlightLastOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteNextPageOptionIntent: _AutocompleteCallbackAction( + onInvoke: _highlightNextPageOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompletePreviousPageOptionIntent: + _AutocompleteCallbackAction( + onInvoke: _highlightPreviousPageOption, + isEnabledCallback: () => _canShowOptionsView, + ), DismissIntent: CallbackAction(onInvoke: _hideOptions), }; @@ -352,9 +374,33 @@ class _RawAutocompleteState extends State> String? _lastFieldText; final ValueNotifier _highlightedOptionIndex = ValueNotifier(0); - static const Map _shortcuts = { + static const Map _appleShortcuts = { + SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): AutocompleteFirstOptionIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): AutocompleteLastOptionIntent(), + }; + + static const Map _nonAppleShortcuts = { + SingleActivator(LogicalKeyboardKey.arrowUp, control: true): AutocompleteFirstOptionIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown, control: true): AutocompleteLastOptionIntent(), + }; + + static const Map _commonShortcuts = { SingleActivator(LogicalKeyboardKey.arrowUp): AutocompletePreviousOptionIntent(), SingleActivator(LogicalKeyboardKey.arrowDown): AutocompleteNextOptionIntent(), + SingleActivator(LogicalKeyboardKey.pageUp): AutocompletePreviousPageOptionIntent(), + SingleActivator(LogicalKeyboardKey.pageDown): AutocompleteNextPageOptionIntent(), + }; + + static Map get _shortcuts => { + ..._commonShortcuts, + ...switch (defaultTargetPlatform) { + TargetPlatform.iOS => _appleShortcuts, + TargetPlatform.macOS => _appleShortcuts, + TargetPlatform.android => _nonAppleShortcuts, + TargetPlatform.linux => _nonAppleShortcuts, + TargetPlatform.windows => _nonAppleShortcuts, + TargetPlatform.fuchsia => _nonAppleShortcuts, + }, }; bool get _canShowOptionsView => _focusNode.hasFocus && _selection == null && _options.isNotEmpty; @@ -421,22 +467,39 @@ class _RawAutocompleteState extends State> _updateOptionsViewVisibility(); } - void _updateHighlight(int newIndex) { - _highlightedOptionIndex.value = _options.isEmpty ? 0 : newIndex % _options.length; + void _updateHighlight(int nextIndex) { + _highlightedOptionIndex.value = _options.isEmpty ? 0 : nextIndex.clamp(0, _options.length - 1); } void _highlightPreviousOption(AutocompletePreviousOptionIntent intent) { - assert(_canShowOptionsView); - _updateOptionsViewVisibility(); - assert(_optionsViewController.isShowing); - _updateHighlight(_highlightedOptionIndex.value - 1); + _highlightOption(_highlightedOptionIndex.value - 1); } void _highlightNextOption(AutocompleteNextOptionIntent intent) { + _highlightOption(_highlightedOptionIndex.value + 1); + } + + void _highlightFirstOption(AutocompleteFirstOptionIntent intent) { + _highlightOption(0); + } + + void _highlightLastOption(AutocompleteLastOptionIntent intent) { + _highlightOption(_options.length - 1); + } + + void _highlightNextPageOption(AutocompleteNextPageOptionIntent intent) { + _highlightOption(_highlightedOptionIndex.value + _pageSize); + } + + void _highlightPreviousPageOption(AutocompletePreviousPageOptionIntent intent) { + _highlightOption(_highlightedOptionIndex.value - _pageSize); + } + + void _highlightOption(int index) { assert(_canShowOptionsView); _updateOptionsViewVisibility(); assert(_optionsViewController.isShowing); - _updateHighlight(_highlightedOptionIndex.value + 1); + _updateHighlight(index); } Object? _hideOptions(DismissIntent intent) { @@ -766,10 +829,36 @@ class AutocompleteNextOptionIntent extends Intent { const AutocompleteNextOptionIntent(); } +/// An [Intent] to highlight the first option in the autocomplete list. +class AutocompleteFirstOptionIntent extends Intent { + /// Creates an instance of AutocompleteFirstOptionIntent. + const AutocompleteFirstOptionIntent(); +} + +/// An [Intent] to highlight the last option in the autocomplete list. +class AutocompleteLastOptionIntent extends Intent { + /// Creates an instance of AutocompleteLastOptionIntent. + const AutocompleteLastOptionIntent(); +} + +/// An [Intent] to highlight the option one page after the currently highlighted +/// option in the autocomplete list. +class AutocompleteNextPageOptionIntent extends Intent { + /// Creates an instance of AutocompleteNextPageOptionIntent. + const AutocompleteNextPageOptionIntent(); +} + +/// An [Intent] to highlight the option one page before the currently +/// highlighted option in the autocomplete list. +class AutocompletePreviousPageOptionIntent extends Intent { + /// Creates an instance of AutocompletePreviousPageOptionIntent. + const AutocompletePreviousPageOptionIntent(); +} + /// An inherited widget used to indicate which autocomplete option should be /// highlighted for keyboard navigation. /// -/// The `RawAutoComplete` widget will wrap the options view generated by the +/// The `RawAutocomplete` widget will wrap the options view generated by the /// `optionsViewBuilder` with this widget to provide the highlighted option's /// index to the builder. /// diff --git a/packages/flutter/test/material/autocomplete_test.dart b/packages/flutter/test/material/autocomplete_test.dart index 3b7c72f6f9..80ee55b210 100644 --- a/packages/flutter/test/material/autocomplete_test.dart +++ b/packages/flutter/test/material/autocomplete_test.dart @@ -596,4 +596,56 @@ void main() { expect(find.text('aa').hitTestable(), findsOneWidget); }); }); + + testWidgets('can jump to options that are not yet built', (WidgetTester tester) async { + const Color highlightColor = Color(0xFF112233); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData.light().copyWith(focusColor: highlightColor), + home: Scaffold( + body: Autocomplete( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + ), + ), + ), + ); + + await tester.tap(find.byType(TextFormField)); + await tester.pump(); + expect(find.byType(ListView), findsOneWidget); + final ListView list = find.byType(ListView).evaluate().first.widget as ListView; + expect(list.semanticChildCount, kOptions.length); + + Finder optionFinder(int index) { + return find.ancestor( + matching: find.byType(Container), + of: find.text(kOptions.elementAt(index)), + ); + } + + expect(optionFinder(0), findsOneWidget); + expect(optionFinder(kOptions.length - 1), findsNothing); + + // Jump to the bottom. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pumpAndSettle(); + expect(optionFinder(0), findsNothing); + expect(optionFinder(kOptions.length - 1), findsOneWidget); + checkOptionHighlight(tester, kOptions.last, highlightColor); + + // Jump to the top. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pumpAndSettle(); + expect(optionFinder(0), findsOneWidget); + expect(optionFinder(kOptions.length - 1), findsNothing); + checkOptionHighlight(tester, kOptions.first, highlightColor); + }); } diff --git a/packages/flutter/test/widgets/autocomplete_test.dart b/packages/flutter/test/widgets/autocomplete_test.dart index c32b120a32..e42125624b 100644 --- a/packages/flutter/test/widgets/autocomplete_test.dart +++ b/packages/flutter/test/widgets/autocomplete_test.dart @@ -1527,12 +1527,13 @@ void main() { expect(lastOptions, ['dingo', 'flamingo']); }); - testWidgets('can navigate options with the keyboard', (WidgetTester tester) async { + testWidgets('can navigate options with the arrow keys', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; + late int lastHighlighted; await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -1564,6 +1565,7 @@ void main() { AutocompleteOnSelected onSelected, Iterable options, ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); lastOptions = options; return Container(key: optionsKey); }, @@ -1607,19 +1609,209 @@ void main() { expect(lastOptions.elementAt(4), 'mouse'); expect(lastOptions.elementAt(5), 'northern white rhinoceros'); - // The selection should wrap at the top and bottom. Move up to 'mouse' - // and then back down to 'goose' and select it. + // Selection does not wrap (going up). await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); + + // Selection does not wrap (going down). await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 1); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 2); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 3); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); + }); + + testWidgets('can jump to ends with keyboard', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable lastOptions; + late FocusNode focusNode; + late TextEditingController textEditingController; + late int lastHighlighted; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextFormField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + onFieldSubmitted: (String value) { + onFieldSubmitted(); + }, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected onSelected, + Iterable options, + ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + // Enter text. The options are filtered by the text. + focusNode.requestFocus(); + textEditingController.clear(); + await tester.enterText(find.byKey(fieldKey), 'e'); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); - expect(find.byKey(optionsKey), findsNothing); - expect(textEditingController.text, 'goose'); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); + + // Jump to the bottom. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 5); + + // Doesn't wrap down. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 5); + + // Jump to the top. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 0); + + // Doesn't wrap up. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 0); + }); + + testWidgets('can navigate with page up/down keys', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable lastOptions; + late FocusNode focusNode; + late TextEditingController textEditingController; + late int lastHighlighted; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextFormField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + onFieldSubmitted: (String value) { + onFieldSubmitted(); + }, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected onSelected, + Iterable options, + ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + // Enter text. The options are filtered by the text. + focusNode.requestFocus(); + textEditingController.clear(); + await tester.enterText(find.byKey(fieldKey), 'e'); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); + + // Jump down. Stops at the bottom and doesn't wrap. + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 5); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 5); + + // Jump to the bottom and then jump up a page. + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 1); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 0); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 0); }); testWidgets('can hide and show options with the keyboard', (WidgetTester tester) async { @@ -1863,10 +2055,22 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(lastHighlighted, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); // And move it back up await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); expect(lastHighlighted, 2); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); @@ -1875,10 +2079,10 @@ void main() { await tester.pump(); expect(lastHighlighted, 0); - // Going back up should wrap around + // Arrow keys do not wrap. await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); - expect(lastHighlighted, 5); + expect(lastHighlighted, 0); }, );