Flutter使用flutter_typeahead时出现返回类型不匹配报错
报错原因
类型不匹配问题由两个问题共同触发:
suggestionsCallback回调强制要求返回非空的Future<Iterable<T>>类型值,但你定义的fetchPlaceSuggestions返回值是带可空标记的Future<List<String>?>,允许返回null,不符合回调的类型约束。- 你的
fetchPlaceSuggestions方法中,List.generate逻辑直接返回了predictions数组里的原始Map对象,没有提取字符串字段,实际生成的是List<dynamic>,和声明的List<String>类型也不匹配,进一步导致类型推断失败。
另外你写的请求地址'{$_baseUrl}autocomplete/json?'多了一层大括号,实际请求会拼接出错误的url,这个顺带修复即可。
修复方案
按以下两步修改即可:
- 调整
fetchPlaceSuggestions方法:去掉返回值的可空标记,请求失败时返回空列表而非null,同时修正列表生成逻辑,提取Google Places接口返回的地址文本字段(通常是description字段),顺手修正url的拼写错误。
Future<List<String>> fetchPlaceSuggestions(String searchText) async { final response = await _dioClient.get( '$_baseUrl/autocomplete/json?', queryParameters: { 'input': searchText, 'key': googleAPIKey, }, ); if (response.statusCode == 200) { final predictions = response.data['predictions'] as List; // 提取地址描述字段生成字符串列表 return predictions.map((item) => item['description'] as String).toList(); } // 请求失败返回空列表,符合非空要求 return []; }
- 给
TypeAheadField显式指定泛型为String,和建议项的类型对齐,避免Dart类型推断出错:
TypeAheadField<String>( 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 PlacesRepository.fetchPlaceSuggestions(searchPattern); }, // 按需补全itemBuilder、onSuggestionSelected等必选参数即可 )
补充:如果后续需要获取地点ID、经纬度等更多信息,可以自定义Place实体类,将方法返回值改为
Future<List<Place>>,同时把TypeAheadField的泛型改成Place即可,核心规则是不要给返回值加可空标记,请求异常时返回空列表。
内容的提问来源于stack exchange,提问作者strangeCat
相关产品推荐
相关产品推荐

