扑动中的Api自动组合搜索



我想在我的应用程序中实现一个搜索文本字段,该字段从API获得结果。但问题是,我在文本字段的onChanged上调用API,例如,当你首先键入"ab"时,它会为"a"的结果调用API,由于需要一些时间才能得到结果,除非用户键入得很慢,否则它永远不会调用"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)),
),

您可以使用flatter_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文档,请参阅文档。

最新更新