我正在嘗試使用 flutter [Typeahead] https://pub.dev/packages/flutter_typeahead包為用戶顯示建議。我得到“回傳型別'串列?不是閉包背景關系所要求的“Future<Iterable<_>>”。我按照檔案中的示例進行操作,但無法使其作業。
TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: 'Search Location',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
),
),
),
suggestionsCallback: (searchPattern) async {
return await PlacesRepository.fetchPlaceSuggestions(searchPattern); /// error here
},
),
fetchPlaceSuggestions():
Future<List<String>?> fetchPlaceSuggestions(String searchText) async {
// Fetch result for the search pattern
final response =
await _dioClient.get('{$_baseUrl}autocomplete/json?', queryParameters: {
'input': searchText,
'key': googleAPIKey,
});
// Check if response is successfull
if (response.statusCode == 200) {
return List.generate(response.data['predictions'].length, (index) {
return response.data['predictions'][index];
});
}
return null;
}
謝謝。干杯
uj5u.com熱心網友回復:
首先,洗掉asyncin return await PlacesRepository.fetchPlaceSuggestions(searchPattern);,或者你得到的是 a value,而不是 a Future<value>,它與suggestionsCallback欄位型別宣告不兼容。
其次,去掉中的問號Future<List<String>?>,原因是一樣的。然后它就起作用了。
演示代碼:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Scroll'),
),
bottomNavigationBar: BottomNavigationBar(
// currentIndex: _selectedScreenIndex,
// onTap: _selectScreen,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Screen A'),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: "Screen B")
],
),
body: Container(
child: TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
style: DefaultTextStyle.of(context)
.style
.copyWith(fontStyle: FontStyle.italic),
decoration: InputDecoration(border: OutlineInputBorder())),
suggestionsCallback: (pattern) async {
return fetchPlaceSuggestions();
},
itemBuilder: (context, suggestion) {
return ListTile(
leading: Icon(Icons.shopping_cart),
);
},
onSuggestionSelected: (suggestion) {
// Navigator.of(context).push(MaterialPageRoute(
// builder: (context) => ProductPage(product: suggestion)));
print("to page .......");
},
),
),
);
}
Future<List<String>> fetchPlaceSuggestions() async {
return Future.value(List.generate(2, (index) {
return ['a', 'b'][index];
}));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/496052.html
