如何禁用TypeAheadField的无结果提示及获取未匹配输入文本
使用TypeAheadField组件的两个问题咨询
- 如何完全禁用(而非修改提示内容)组件的“No Items Found”提示;
- 如何获取TypeAheadField中输入的、未匹配任何建议项的文本内容。
我的TypeAheadField实现代码:
TypeAheadField<PostListOfProducts?>( hideSuggestionsOnKeyboardHide: false, minCharsForSuggestions: 2, textFieldConfiguration: TextFieldConfiguration( controller: _typeAheadController, decoration: const InputDecoration( prefixIcon: Icon(Icons.search), filled: true, fillColor: Colors.white, hintText: 'Wyszukaj produkt', hintStyle: TextStyle(fontSize: 16.0, color: Colors.blue), ), ), suggestionsCallback: ApiDataSingleton.instance.productSuggestions, itemBuilder: (context, PostListOfProducts? suggestion) { final post = suggestion!; return ListTile( title: Text(post.nazwa!), ); }, noItemsFoundBuilder: (context) { return const SizedBox(height: 40, child: Center(child: Text('Brak produktów', style: TextStyle(fontSize: 16)))); }, onSuggestionSelected: (PostListOfProducts? suggestion) { final post = suggestion!; setState(() { _name = post.nazwa.toString(); _typeAheadController.text = post.nazwa.toString(); }); }, )
解决方案
1. 完全禁用“No Items Found”提示
将noItemsFoundBuilder设置为返回一个高度为0的空容器,或者直接设为null,即可彻底隐藏无匹配项时的提示内容:
修改后的代码片段:
TypeAheadField<PostListOfProducts?>( // 其他参数保持不变 noItemsFoundBuilder: (context) => SizedBox.shrink(), // 其他参数保持不变 )
2. 获取未匹配建议项的输入文本
你已经通过_typeAheadController绑定了输入框,直接通过该控制器即可获取当前输入的文本,无需额外配置。常用的获取时机包括:
方式1:通过输入框回调获取
在textFieldConfiguration中添加onSubmitted或onEditingComplete回调,在用户完成输入时获取文本:
textFieldConfiguration: TextFieldConfiguration( controller: _typeAheadController, decoration: const InputDecoration( // 原有装饰参数不变 ), onSubmitted: (inputText) { // inputText即为当前输入的文本,无论是否匹配建议项 print("输入内容:$inputText"); }, onEditingComplete: () { String currentText = _typeAheadController.text; // 处理输入文本的逻辑 }, ),
方式2:实时监听文本变化
在initState中添加控制器监听,实时获取输入的文本:
@override void initState() { super.initState(); _typeAheadController.addListener(() { String currentText = _typeAheadController.text; // 实时处理文本的逻辑 }); } @override void dispose() { _typeAheadController.dispose(); super.dispose(); }
内容的提问来源于stack exchange,提问作者bzc0fq
相关产品推荐
相关产品推荐

