首页 > 解决方案 > 如何在颤动中限制onLocationChanged

问题描述

我想每 10 分钟更新一次用户的位置。工作正常,onLocationChanged即使应用程序在后台。但是,当位置更改时,它会不断抛出位置详细信息。我希望它_getCurrentLocationtoServer()在 10 分钟后运行一个方法。

location.onLocationChanged.listen((LocationData cLoc) {
      currentLocation = cLoc;
      _getCurrentLocationtoServer();
    });

void _getCurrentLocationtoServer() async{
//code to send to server
}

我正在使用https://pub.dev/packages/location包。

标签: flutterdartgeolocationlocation

解决方案


不要在 onLocationChanged 中调用 _getCurrentLocationtoServer()。只需分配 currentLocation 值。现在,做一个新的

Timer.periodic(Duration(minutes: 10), () => _getCurrentLocationtoServer());

这会定期运行,并每 10 分钟向服务器发送一次 currentLocation 值。在将 currentLocation 值发送到服务器之前,请确保它不为空。


推荐阅读