You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:12:31