Flutter向Firebase Firestore添加LatLng字段时遇类型转换运行时错误
问题描述
在使用Dart开发的Flutter应用中,执行以下代码向Firebase Firestore对象添加字段时:
geolocation: LatLng(latitude, longitude),
出现运行时错误:
无效参数(dartObject):无法转换类型为'LatLng'的实例
解决方案
Firestore不直接支持LatLng类型,需转换成它可识别的格式,两种常用处理方式:
方式一:使用Firestore原生GeoPoint类型
用Firebase提供的GeoPoint类替换LatLng,修改代码为:geolocation: GeoPoint(latitude, longitude),读取数据时再转回
LatLng:final geoPoint = doc.data()['geolocation'] as GeoPoint; final latLng = LatLng(geoPoint.latitude, geoPoint.longitude);方式二:以Map格式存储经纬度
把经纬度拆成键值对存入Firestore:geolocation: { 'latitude': latitude, 'longitude': longitude },读取时从Map中取值构建
LatLng:final geoMap = doc.data()['geolocation'] as Map<String, double>; final latLng = LatLng(geoMap['latitude']!, geoMap['longitude']!);
内容的提问来源于stack exchange,提问作者YEG
相关产品推荐
相关产品推荐

