You need to enable JavaScript to run this app. Flutter开发中获取定位与地图标记时触发latitude空值调用异常排查
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发中获取定位与地图标记时触发latitude空值调用异常排查

Flutter Google地图空引用异常排查与修复

项目实现的核心功能

  • 加载自定义样式Google地图
  • 集成geolocator插件获取用户当前位置
  • 从Firebase Firestore的points集合拉取点位数据,渲染自定义标记
  • 标记点击触发底部详情面板弹出

异常表现

页面最终可正常展示地图效果,但控制台持续抛出空引用错误:

The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude

完整报错栈

Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building Map(dirty, state: _NewMapState#22070):
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude

The relevant error-causing widget was
Map
lib\Pages\home.dart:46
When the exception was thrown, this was the stack
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _NewMapState.mapWidget
package:map/Pages/test.dart:106
#2      _NewMapState.build
package:map/Pages/test.dart:97
#3      StatefulElement.build
package:flutter/…/widgets/framework.dart:4744
#4      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4627
...

根因定位

异常由三个叠加的代码缺陷触发:

  1. 竞态条件导致空状态下构建地图组件
    定位流程为异步执行,getCurrentLocation方法未对定位结果做空值校验、未捕获定位过程的异常。当定位流程因为权限、服务状态问题返回空值、或被异常打断时,仍会执行setState将组件替换为地图视图;而地图视图的初始化相机位置直接读取position.latitude,此时position为null,就会触发空引用异常。后续定位流程补全位置信息后页面重新渲染,最终展示效果看似正常,但首次异常已被Flutter框架捕获上报。
  2. 数据拉取流程无字段校验
    从Firestore拉取点位数据时,未提前判断文档中location字段的有效性。如果某条文档缺失位置字段、值为null,直接访问tomb['location'].latitude时就会触发空引用。
  3. 异步回调未做组件状态校验
    所有异步流程(定位、Firestore拉取、图标加载)执行setState时,未判断组件是否仍处于挂载状态,也未对依赖的资源(位置数据、自定义标记图标)做就绪判断,导致资源未加载完成时就触发组件重建。

修复方案

1. 重构定位流程,增加全链路空值与异常保护

  • 定位前先检查定位服务状态、权限状态
  • 定位结果非空才更新组件状态
  • 捕获定位流程的所有异常,避免流程中断
    示例实现:
void getCurrentLocation() async {
  try {
    // 检查定位服务是否开启
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) return;

    // 检查并申请定位权限
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
        return;
      }
    }

    // 获取定位结果
    Position res = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    // 仅当组件挂载、定位结果有效时更新状态
    if (mounted && res != null) {
      setState(() {
        position = res;
      });
    }
  } catch (e) {
    debugPrint('定位流程异常: $e');
  }
}

2. 优化点位数据校验逻辑

添加标记前先判断字段有效性,跳过无效文档

void initMarker(tomb, tombId) {
  // 校验位置字段与图标资源就绪状态
  final location = tomb['location'];
  if (location == null || pinLocationIcon == null) {
    debugPrint('文档 $tombId 数据无效,跳过标记添加');
    return;
  }

  final markerId = MarkerId(tombId);
  final marker = Marker(
    markerId: markerId,
    position: LatLng(location.latitude, location.longitude),
    icon: pinLocationIcon,
    infoWindow: InfoWindow(title: 'Shop', snippet: tombId),
    onTap: () => _settingModalBottomSheet(context, tombId),
  );

  if (mounted) {
    setState(() => markers[markerId] = marker);
  }
}

3. 调整build方法的状态判断逻辑

不再完全依赖初始设置的_child变量,根据资源就绪状态动态渲染组件,避免空状态下渲染地图视图:

@override
Widget build(BuildContext context) {
  // 位置数据、自定义图标未就绪时显示加载动画
  if (position == null || pinLocationIcon == null) {
    return Scaffold(body: Center(child: _child));
  }
  // 资源就绪后渲染地图视图
  return Scaffold(body: mapWidget());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 18:15:06