Move cursor position to the end of search query in SearchDelegate after query is set (#83512)

This commit is contained in:
Bikram Pandit
2021-06-05 08:14:04 +05:45
committed by GitHub
parent 921c724dbb
commit 44ebcb66d1
2 changed files with 26 additions and 0 deletions

View File

@@ -248,9 +248,14 @@ abstract class SearchDelegate<T> {
/// If the user taps on a suggestion provided by [buildSuggestions] this
/// string should be updated to that suggestion via the setter.
String get query => _queryTextController.text;
/// Changes the current query string.
///
/// Setting the query string programmatically moves the cursor to the end of the text field.
set query(String value) {
assert(query != null);
_queryTextController.text = value;
_queryTextController.selection = TextSelection.fromPosition(TextPosition(offset: _queryTextController.text.length));
}
/// Transition from the suggestions returned by [buildSuggestions] to the

View File

@@ -40,6 +40,27 @@ void main() {
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
});
testWidgets('Changing query moves cursor to the end of query', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
await tester.pumpWidget(TestHomePage(delegate: delegate));
await tester.tap(find.byTooltip('Search'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
delegate.query = 'Foo';
final TextField textField = tester.widget<TextField>(find.byType(TextField));
expect(
textField.controller!.selection,
TextSelection(
baseOffset: delegate.query.length,
extentOffset: delegate.query.length,
),
);
});
testWidgets('Can open and close search', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
final List<String> selectedResults = <String>[];