When entering a search term in Flutter’s SearchAnchor/SearchBar widget, it’s natural to press the enter key to submit the search. There isn’t an obvious way to listen for this event though. There isn’t a "onSubmitted" callback like TextField has.
So, how can I detect when the enter key was pressed so I can close the SearchAnchor/SearchBar and show the search results?
Note: This question refers to the SearchBar / SearchAnchor widgets first released in Flutter 3.10.0
I’ve examined the SearchAnchor/SearchBar API and experimented with various approaches for discovering when the user taps the enter key, as noted in this code snippet:
import 'package:flutter/material.dart';
class SearchView extends StatefulWidget {
const SearchView({super.key});
@override
State<SearchView> createState() => _SearchViewState();
}
class _SearchViewState extends State<SearchView> {
final searchController = SearchController();
@override
void initState() {
searchController.addListener(() {
// Not called when enter key pressed.
});
super.initState();
}
@override
Widget build(BuildContext context) {
return SearchAnchor(
// No onSubmitted callback parameter.
searchController: searchController,
builder: (context, controller) {
return SearchBar(
// No onSubmitted callback parameter
onTap: () => controller.openView(),
controller: controller,
onChanged: (text) {
// Not called when enter key pressed.
},
);
},
suggestionsBuilder: (context, controller) {
// Enter character not found in controller.text
return [];
},
);
}
}
2
Answers
Wrap your textfield/searchbar/anything-with-text in a
RawKeyboardListener
widget. Docs here.In short, your code will look like this:
If you want to close the textfield-type thing on the enter key being pressed and clear the text, do something like this:
Hopefully this helps!
There is an isuue and related pull request on Flutter’s repo.