使用google_places_flutter点击搜索结果触发空值检查异常
问题:google_places_flutter点击搜索项触发空值检查异常
我在Flutter中使用google_places_flutter库实现Google地图搜索功能,代码如下:
GooglePlaceAutoCompleteTextField( textEditingController: _searchController, googleAPIKey: mapKey, isCrossBtnShown: false, radius: 16, inputDecoration: const InputDecoration( hintText: "Search Location...", border: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black54), borderRadius: BorderRadius.zero, ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black54), borderRadius: BorderRadius.zero, ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.blue), ), focusedErrorBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.red), borderRadius: BorderRadius.zero, ), contentPadding: EdgeInsets.only(left: 12.0), fillColor: Colors.transparent, filled: false, ), boxDecoration: BoxDecoration( borderRadius: BorderRadius.circular(0.0), ), debounceTime: 800, isLatLngRequired: true, getPlaceDetailWithLatLng: onPlaceSelected, ), void onPlaceSelected(dynamic place) async { double lat = place['geometry']['location']['lat']; double lng = place['geometry']['location']['lng']; await _updateLocation(lat, lng); }
搜索时API能正常返回下拉列表,但点击列表项时抛出异常:google_places_flutter : Unhandled Exception: Null check operator used on a null value,推测该错误并非由我的业务代码导致。
可能的解决方案
1. 临时添加空值防护
即便设置了isLatLngRequired: true,仍可能存在库未正确校验API返回字段的情况,在onPlaceSelected中增加空判断避免崩溃:
void onPlaceSelected(dynamic place) async { if (place != null && place['geometry'] != null && place['geometry']['location'] != null) { double? lat = place['geometry']['location']['lat']; double? lng = place['geometry']['location']['lng']; if (lat != null && lng != null) { await _updateLocation(lat, lng); } } }
2. 升级库到最新版本
该空值异常大概率是库内部的空安全问题,检查pubspec.yaml中google_places_flutter的版本,升级到最新版后重新测试,很多类似的空值bug会在新版本中修复。
3. 替换为更可靠的实现方式
如果升级后问题仍存在,建议放弃第三方封装库,直接使用官方的google_maps_webservice库实现自动补全:
- 调用Autocomplete API获取搜索建议列表
- 自定义下拉列表UI,点击后调用Place Details API获取经纬度
- 这种方式更可控,能避免第三方库的潜在问题
内容的提问来源于stack exchange,提问作者Kirtan
相关产品推荐
相关产品推荐

