当在Flutter的SearchAnchor/SearchBar小部件中输入搜索词时,按回车键提交搜索是很自然的。不过,对于SearchAnchor/SearchBar,似乎没有与TextField的onSubmitted回调等效的回调。我如何检测到输入键被按下,以便我可以关闭搜索锚点/搜索栏并显示搜索结果?
注意:这个问题是指Flutter 3.10.0中首次发布的SearchBar / SearchAnchor小部件
我已经研究了SearchAnchor/SearchBar API,并尝试了各种方法来发现用户何时点击回车键,如以下代码片段所示:
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 [];
},
// No onSubmitted callback.
);
}
}
1条答案
按热度按时间g52tjvyc1#
将你的textfield/searchbar/anything-with-text封装在一个
RawKeyboardListener
小部件中。Docs here。简而言之,你的代码看起来像这样:
如果你想在按下回车键时关闭文本字段类型的东西并清除文本,请执行以下操作:
希望这有帮助!