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

Flutter Web中LegacyJavaScriptObject转GeoPoint失败问题排查

Web端StreamBuilder GeoPoint类型不匹配问题解决

针对你遇到的Android/iOS正常但Web端抛出Expected a value of type 'GeoPoint', but got one of type 'LegacyJavaScriptObject'的问题,这是Flutter Web与Firestore JS SDK交互时的类型映射bug,以下是几个可行的解决办法:

1. 实体类解析时强制转换GeoPoint

在Branch的fromJson方法里,针对Web平台显式把JS对象转成Dart的GeoPoint:

import 'dart:js' as js;
import 'package:flutter/foundation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class Branch {
  final GeoPoint location;

  Branch({required this.location});

  factory Branch.fromJson(Map<String, dynamic> json) {
    var locationRaw = json['location'];
    GeoPoint location;
    
    if (kIsWeb && locationRaw is js.JsObject) {
      // 直接从JS对象取经纬度构造GeoPoint
      location = GeoPoint(
        locationRaw['latitude'],
        locationRaw['longitude'],
      );
    } else {
      location = locationRaw as GeoPoint;
    }
    
    return Branch(location: location);
  }
}

2. 对齐cloud_firestore_web版本

检查pubspec.lock里cloud_firestore_web的版本,必须和cloud_firestore主版本一致(比如4.15.3对应3.15.3),如果不一致,手动在pubspec.yaml指定:

dependencies:
  cloud_firestore: 4.15.3
  cloud_firestore_web: 3.15.3

3. 彻底清理缓存重建Web项目

缓存问题经常导致Web端依赖异常,执行以下命令:

flutter clean
flutter pub get
cd web && rm -rf build .dart_tool && cd ..
flutter build web

4. 确保流提前解析实体

检查myBranches流提供者的逻辑,必须在流内部完成Branch的解析,不要把原始快照传到StreamBuilder里处理:

Stream<List<Branch>> get myBranches {
  return FirebaseFirestore.instance
      .collection('branches')
      .snapshots()
      .map((snap) => snap.docs.map((doc) => Branch.fromJson(doc.data())).toList());
}

5. 升级到最新稳定版依赖

如果降级没用,试试升级到最新兼容的Firebase版本,可能官方已经修复了这个Web端的类型bug:

firebase_core: ^2.26.0
cloud_firestore: ^4.16.0

升级后记得重复步骤3清理缓存。


内容的提问来源于stack exchange,提问作者BillyParadise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:02:44