Flutter集成Google Places API(新版)无法显示地点问题排查
排查Flutter集成Google Places API地点建议不显示的问题
以下是针对你代码的具体排查点和修复建议:
1. 处理API返回的隐性错误(状态码200仍可能报错)
Google Places API返回200状态码时,仍可能通过error_message或status字段提示问题(比如密钥权限不足、配额耗尽、参数非法)。你的代码目前忽略了这类情况,导致无结果时无法定位原因。
修改fetchAutocompleteSuggestions方法,补充错误判断:
if (response.statusCode == 200) { final data = json.decode(response.body); // 新增:捕获API返回的错误信息 if (data['error_message'] != null) { throw Exception('API错误: ${data['error_message']}'); } if (data['status'] != 'OK') { throw Exception('API状态异常: ${data['status']}'); } final predictions = data['predictions'] as List; return predictions.map((prediction) { return { 'description': prediction['description'].toString(), 'placeId': prediction['place_id'].toString(), }; }).toList(); } else { throw Exception('请求失败: ${response.statusCode}'); }
2. 对URL参数进行编码
如果输入的地点包含空格、中文或特殊字符,直接拼接URL会导致请求格式错误。改用Uri.https自动处理参数编码:
final url = Uri.https( 'maps.googleapis.com', '/maps/api/place/autocomplete/json', { 'input': input, 'key': apiKey, 'language': language, 'components': 'country:$country', }, ); final response = await http.get(url);
(同样修改fetchNearbyAutocompleteSuggestions和fetchPlaceDetails的URL构建逻辑)
3. 为TypeAheadField添加异常捕获与调试
suggestionsCallback抛出异常时,TypeAheadField不会主动提示,导致你看不到错误原因。添加捕获逻辑并打印日志:
suggestionsCallback: (pattern) async { try { final suggestions = await placesService.fetchAutocompleteSuggestions( pattern, widget.countryInitial, ); print('获取到的建议: $suggestions'); // 调试用日志 return suggestions; } catch (e) { print('获取地点建议失败: $e'); Fluttertoast.showToast(msg: '加载地点失败: $e'); return []; } },
4. 完善TypeAheadField的基础配置
- 添加
debounceDuration避免输入过快导致的频繁请求:TypeAheadField( debounceDuration: const Duration(milliseconds: 300), // 其他配置... ) - 添加无结果提示,明确告知用户当前输入无匹配:
noItemsFoundBuilder: (context) { return const ListTile(title: Text('未找到匹配地点')); },
5. 验证核心参数合法性
- 确认
widget.countryInitial是两位ISO国家代码(如'CN'、'US'),非法值会过滤所有结果; - 检查
widget.language是Google Places API支持的语言代码(如'zh-CN'、'en-US'),错误代码可能导致无返回。
6. 检查网络权限
- Android:确保
AndroidManifest.xml中添加了<uses-permission android:name="android.permission.INTERNET"/>; - iOS:确认
Info.plist未禁用HTTPS请求(默认允许,若有NSAppTransportSecurity配置需放行maps.googleapis.com)。
内容的提问来源于stack exchange,提问作者EBENEZER OCANSEY
相关产品推荐
相关产品推荐

