Autocomplete keyboard navigation (#159455)

I noticed some problems with Autocomplete keyboard navigation:

* Previously, when wrapping from the top to bottom or vice-versa,
scrolling wouldn't happen until after you hit the arrow key a few extra
times. This is due to the way we were doing scrolling and the fact that
those items were not yet built by ListView.builder. I fixed this.

<details>

<summary>Video of scrolling bug</summary>

[Screencast from 2024-11-25
16-21-06.webm](https://github.com/user-attachments/assets/ce01065a-1a03-4f37-b0f6-2d6273852ac4)

</details>

* This wrapping feature itself seemed to not be part of the `<select>`
tag on web ([try it on
MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select)),
which Autocomplete is kind of based on, so I removed it. It now stops at
the top/bottom.
* We were missing a couple of keyboard shortcuts
(https://github.com/flutter/flutter/issues/85233)

Fixes https://github.com/flutter/flutter/issues/85233
This commit is contained in:
Justin McCandless
2025-01-23 10:48:41 -08:00
committed by GitHub
parent c1561a41c5
commit 3baa356f52
4 changed files with 450 additions and 46 deletions

View File

@@ -180,55 +180,114 @@ class _AutocompleteOptions<T extends Object> extends StatelessWidget {
});
final AutocompleteOptionToString<T> displayStringForOption;
final AutocompleteOnSelected<T> onSelected;
final OptionsViewOpenDirection openDirection;
final Iterable<T> 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<T>(
displayStringForOption: displayStringForOption,
highlightedIndex: highlightedIndex,
onSelected: onSelected,
options: options,
),
),
),
);
}
}
class _AutocompleteOptionsList<T extends Object> extends StatefulWidget {
const _AutocompleteOptionsList({
required this.displayStringForOption,
required this.highlightedIndex,
required this.onSelected,
required this.options,
});
final AutocompleteOptionToString<T> displayStringForOption;
final int highlightedIndex;
final AutocompleteOnSelected<T> onSelected;
final Iterable<T> options;
@override
State<_AutocompleteOptionsList<T>> createState() => _AutocompleteOptionsListState<T>();
}
class _AutocompleteOptionsListState<T extends Object> extends State<_AutocompleteOptionsList<T>> {
final ScrollController _scrollController = ScrollController();
@override
void didUpdateWidget(_AutocompleteOptionsList<T> 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)),
);
},
),
);
},
);
}
}

View File

@@ -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<T extends Object> extends State<RawAutocomplete<T>>
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<T extends Object> extends State<RawAutocomplete<T>>
onInvoke: _highlightNextOption,
isEnabledCallback: () => _canShowOptionsView,
),
AutocompleteFirstOptionIntent: _AutocompleteCallbackAction<AutocompleteFirstOptionIntent>(
onInvoke: _highlightFirstOption,
isEnabledCallback: () => _canShowOptionsView,
),
AutocompleteLastOptionIntent: _AutocompleteCallbackAction<AutocompleteLastOptionIntent>(
onInvoke: _highlightLastOption,
isEnabledCallback: () => _canShowOptionsView,
),
AutocompleteNextPageOptionIntent: _AutocompleteCallbackAction<AutocompleteNextPageOptionIntent>(
onInvoke: _highlightNextPageOption,
isEnabledCallback: () => _canShowOptionsView,
),
AutocompletePreviousPageOptionIntent:
_AutocompleteCallbackAction<AutocompletePreviousPageOptionIntent>(
onInvoke: _highlightPreviousPageOption,
isEnabledCallback: () => _canShowOptionsView,
),
DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions),
};
@@ -352,9 +374,33 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
String? _lastFieldText;
final ValueNotifier<int> _highlightedOptionIndex = ValueNotifier<int>(0);
static const Map<ShortcutActivator, Intent> _shortcuts = <ShortcutActivator, Intent>{
static const Map<ShortcutActivator, Intent> _appleShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): AutocompleteFirstOptionIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): AutocompleteLastOptionIntent(),
};
static const Map<ShortcutActivator, Intent> _nonAppleShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowUp, control: true): AutocompleteFirstOptionIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown, control: true): AutocompleteLastOptionIntent(),
};
static const Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowUp): AutocompletePreviousOptionIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): AutocompleteNextOptionIntent(),
SingleActivator(LogicalKeyboardKey.pageUp): AutocompletePreviousPageOptionIntent(),
SingleActivator(LogicalKeyboardKey.pageDown): AutocompleteNextPageOptionIntent(),
};
static Map<ShortcutActivator, Intent> get _shortcuts => <ShortcutActivator, Intent>{
..._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<T extends Object> extends State<RawAutocomplete<T>>
_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.
///

View File

@@ -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<String>(
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);
});
}

View File

@@ -1527,12 +1527,13 @@ void main() {
expect(lastOptions, <String>['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<String> lastOptions;
late FocusNode focusNode;
late TextEditingController textEditingController;
late int lastHighlighted;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
@@ -1564,6 +1565,7 @@ void main() {
AutocompleteOnSelected<String> onSelected,
Iterable<String> 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<String> lastOptions;
late FocusNode focusNode;
late TextEditingController textEditingController;
late int lastHighlighted;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RawAutocomplete<String>(
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<String> onSelected,
Iterable<String> 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<String> lastOptions;
late FocusNode focusNode;
late TextEditingController textEditingController;
late int lastHighlighted;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RawAutocomplete<String>(
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<String> onSelected,
Iterable<String> 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);
},
);