flutter - Flutter中的Api自动完成搜索
问题描述
我想在我的应用程序中实现一个从 API 获取结果的搜索文本字段。但问题是我在文本字段的 onChanged 上调用 API,例如,当您首先键入“ab”时,它会调用 API 以获取“a”的结果,并且由于需要一些时间才能获得结果,除非用户调用“ab”打字很慢。我想要一个类似谷歌的自动完成搜索。
TextField(
controller: searchController.textcontroller.value,
onChanged: (v) {
if (searchController.textcontroller.value.text != null ||
searchController.textcontroller.value.text.length > 0) {
searchController.getResult();
}
},
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search...',
hintStyle: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0)),
),
解决方案
您可以使用 flutter_typeahead: ^3.1.3自动完成来自 API 的文本
这是一个例子
文本字段(小部件):
Card(
elevation: 10.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24.0)),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(24)),
color: Colors.white
),
child: TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
controller: this._typeAheadController,
decoration: InputDecoration( // Text field Decorations goes here
hintText: 'Name*',
prefixIcon: Icon(Icons.edit),
border: InputBorder.none
)
),
suggestionsCallback: (pattern) {
return AutocompleteHelper().getSuggestions(pattern: pattern);
},
itemBuilder: (context, <T> suggestion) { //TODO: replace <T> with your return type
return ListTile(
title: Text(suggestion.nAME),subtitle: Text(suggestion.sYMBOL), //sugestion drop down widget customise here
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (<T> suggestion) { //TODO: replace <T> with your return type
this._typeAheadController.text = suggestion.nAME;
},
onSaved: (value) {
_transaction.name = value;
},
),
),
),
自动完成助手类:
class AutocompleteHelper{
Future getSuggestions({@required String pattern)async{
var body = {'APIKey':'000','qry': (pattern+'%').toString()};//TODO: replace acording to your API
Http.Response result = await Http.post(Uri.parse('yoururl.com/api'),body: body);
//TODO: Handel result according to your API
return result.body;
}
有关更多帮助和 API 文档,请参阅文档。
推荐阅读
- windows - 无法更改 mongod 的 dbPath
- jquery - 使用 jquery 正则表达式从文本中提取 [+-] 小数
- java - G Maps Android Java,最后一个已知的位置标记颜色与位置标记不同,但在运行的应用程序上显示相同的标记颜色
- ajax - 未捕获的类型错误:无法在更改 HTMLSelectElement.onchange 时读取未定义的属性“pop”
- java - 启动相机android权限时崩溃
- laravel - 如何与这个 Laravel Eloquent 查询一起获得总和
- javascript - 元素未使用 jquery 中的每个循环定义
- node.js - 什么时候passport.js失败重定向被击中?
- c# - 如何制作一个可以接收不同对象列表作为参数的通用 Blazor 组件?
- wpf - 在使用文件选择器更改图像的 ImageSource 时,弹出该文件正在使用中