You need to enable JavaScript to run this app. Flutter从JSON API获取Marker并在Google地图展示出现类型错误怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter从JSON API获取Marker并在Google地图展示出现类型错误怎么解决

问题核心成因
  • 代码存在重复JSON解析的逻辑错误:在loadString方法中,已经通过jsonDecode(response.body)把接口返回的字符串格式响应,解析为了List<dynamic>类型的结构化数据,并作为Future的返回值传递给FutureBuilder。
  • 进入FutureBuilder的构建逻辑后,又对已经完成解析的snapshot.data二次调用jsonDecode()方法。而jsonDecode方法要求入参必须是String类型,此时传入的List<dynamic>类型值不符合入参要求,直接触发抛出type 'List<dynamic>' is not a subtype of type 'String'的运行时报错。
具体修复步骤
  • 删除FutureBuilder中重复的jsonDecode逻辑,直接将已经解析完成的snapshot.data强转为列表类型使用
  • 给全链路的方法、变量补充明确的类型声明,消除隐式动态类型带来的运行时风险
  • 对经JSON解析得到的数值类型、字符串类型做显式转换,适配Google地图组件的参数要求
  • 适配新版http插件的参数要求,消除废弃API告警
关键修复代码片段

首先是修正后的loadString方法,明确返回值类型:

Future<List<dynamic>> loadString() async {
  var url = "http://10.0.2.2/GoApp/locations.php";
  // 新版http插件要求传入Uri类型,直接传字符串会触发废弃提示
  var response = await http.get(Uri.parse(url));
  final List<dynamic> responseBody = jsonDecode(response.body);
  print(responseBody);
  return responseBody;
}

然后是修正后的FutureBuilder构建逻辑:

builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
  if (!snapshot.hasData) {
    return const Center(child: CircularProgressIndicator());
  }
  // 直接使用已解析完成的列表,无需二次调用jsonDecode
  List<dynamic> parsedJson = snapshot.data!;

  allMarkers = parsedJson.map((i) {
    return Marker(
      // 显式转字符串,适配MarkerId的入参要求
      markerId: MarkerId(i['loc_id'].toString()),
      position: LatLng(
        // 显式转double,适配LatLng的入参要求
        (i['loc_x'] as num).toDouble(),
        (i['loc_y'] as num).toDouble()
      ),
      onTap: () {},
    );
  }).toList();

  return GoogleMap(
    initialCameraPosition: const CameraPosition(
      target: LatLng(40.7128, -74.0060), 
      zoom: 1.0
    ),
    markers: Set.from(allMarkers),
    onMapCreated: mapCreated,
    mapType: MapType.normal,
    tiltGesturesEnabled: true,
    compassEnabled: true,
    rotateGesturesEnabled: true,
    myLocationEnabled: true,
  );
}

最后修正mapCreated方法的参数类型,避免无类型参数的告警:

void mapCreated(GoogleMapController controller) {
  setState(() {
    _controller = controller;
  });
}

修复完成后可正常加载地图,接口返回的Marker数据会被正确渲染到地图对应坐标点上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 18:24:00