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

Flutter启动报错NoSuchMethodError:getDouble调用在null对象上

错误排查:NoSuchMethodError - 调用getDouble时Receiver为null

错误原因

这个错误的核心是**prefs对象未完成初始化,处于null状态**,导致调用getDouble('lat')时找不到接收者。另外,就算prefs初始化完成,首次运行时SharedPreferences里没有存储lat和lng,getDouble也会返回null,同样可能引发后续计算问题。

解决方法

1. 确保SharedPreferences实例提前初始化

在使用prefs前,必须先通过SharedPreferences.getInstance()获取实例,建议在页面的initState中完成初始化:

SharedPreferences prefs;

@override
void initState() {
  super.initState();
  _initSharedPrefs();
}

void _initSharedPrefs() async {
  prefs = await SharedPreferences.getInstance();
}

2. 处理null值与首次运行场景

调用getDouble前先判断prefs是否可用,同时给未存储的字段设置默认值(比如当前位置的经纬度),避免计算distance时出错:

_userCurrentLocationUpdate(Position updatedPosition) async {
  // 先判断prefs是否初始化,同时给默认值
  double oldLat = prefs?.getDouble('lat') ?? updatedPosition.latitude;
  double oldLng = prefs?.getDouble('lng') ?? updatedPosition.longitude;

  double distance = await Geolocator.distanceBetween(
      oldLat,
      oldLng,
      updatedPosition.latitude,
      updatedPosition.longitude);
  
  Map<String, dynamic> values = {
    "id": prefs?.getString("id"),
    "position": updatedPosition.toJson()
  };

  if (distance >= 50) {
    if (show == Show.RIDER) {
      sendRequest(coordinates: requestModelFirebase.getCoordinates());
    }
    _userServices.updateUserData(values);
    await prefs.setDouble('lat', updatedPosition.latitude);
    await prefs.setDouble('lng', updatedPosition.longitude);
  }
}

3. 提前初始化存储的经纬度

如果是首次启动应用,可以在第一次获取到位置后,直接将当前经纬度存入SharedPreferences,避免后续计算时出现null值:

// 首次获取位置后执行
await prefs.setDouble('lat', initialPosition.latitude);
await prefs.setDouble('lng', initialPosition.longitude);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:58:13