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

如何在Flutter中从Mongo API获取Geometry几何坐标数据

问题排查与修复方案

1. 补全/修正Geometry模型类定义

你当前只给出了Padiglioni类的代码,未提供Geometry类的实现,这是最可能导致坐标无法正常解析的原因。Mongo返回的Geometry是标准GeoJSON结构,需要按返回的字段一一匹配定义,示例代码如下:

class Geometry {
  final String type;
  final List<dynamic> coordinates; // 若为Point类型可转成List<double>,Polygon类型是List<List<List<double>>>

  Geometry({
    required this.type,
    required this.coordinates,
  });

  factory Geometry.fromJson(Map<String, dynamic> json) {
    return Geometry(
      type: json['type'] as String,
      coordinates: json['coordinates'] as List<dynamic>,
    );
  }
}

2. 检查字段匹配性

  • 确认接口返回的Geometry字段名和你代码中json['geometry']的拼写、大小写完全一致,若返回的是大写开头的Geometry,需要修改为json['Geometry']
  • 确认coordinates字段的嵌套层级和你接收的类型匹配:比如Polygon类型的坐标是三层嵌套数组,不能直接用单层List接收

3. 优化Padiglioni类的冗余逻辑

你当前类中check字段默认值为false,factory方法中也是硬编码传false,可以简化构造函数逻辑:

class Padiglioni {
  final String id;
  final String nome;
  final String area;
  bool check;
  final Geometry geometry;

  Padiglioni({
    required this.area,
    required this.id,
    required this.nome,
    this.check = false, // 设为默认值,无需required
    required this.geometry
  });

  factory Padiglioni.fromJson(Map<String, dynamic> json) {
    return Padiglioni(
      id: json['_id'] ?? json['id'] as String, // 注意Mongo默认主键是_id,如果你接口返回的是_id要改这里
      nome: json['nome'] as String,
      area: json['area'] as String,
      geometry: Geometry.fromJson(json['geometry']),
    );
  }
}

4. 排查运行时异常

打开控制台查看是否有类型转换相关的报错,比如type 'List<dynamic>' is not a subtype of type 'List<double>'这类报错,就是coordinates的接收类型和实际返回类型不匹配导致的,按需调整类型定义即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:15:03