Search code examples
androidiosflutterdartlocation

How to set an interval to the flutter location receiving data


I've been trying to get the location data via onLocationChanged() method using Location package. And I got successful too. But the problem is I need to slow/delay the location data receiving from the package. I increased the interval period but but, It didn't worked.

I need to slow the data receiving speed so, that the app will run smoothly, otherwise it's lagging.

This is the code snippet that I followed,

  Location location = new Location();
  StreamSubscription _locationSubscription;

  void initState() { 
    super.initState();
    _animateToUser();
  }

  @override
  void dispose() { 
    if (_locationSubscription != null) {
      _locationSubscription.cancel();
    }    
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        GoogleMap(
          initialCameraPosition: CameraPosition(
            target: LatLng(6.854399, 79.865463),
            zoom: 14.44,
          ),
          myLocationEnabled: true,
          onMapCreated: _onMapCreated,
        ),        
      ],
    );
  }

  _onMapCreated(GoogleMapController controller) {
    setState(() {
      mapController = controller;
    });
  }

  _animateToUser() async {

    location.changeSettings(interval: 3000, distanceFilter: 10.0);
    _locationSubscription = location.onLocationChanged().listen((newData) {

      print(newData.latitude);

      mapController.animateCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            target: LatLng(newData.latitude, newData.longitude), 
            zoom: 17.0
          )
        )
      );

    });

  }

I think the way I defined changeSettings() is maybe wrong.

location.changeSettings(interval: 3000, distanceFilter: 10.0);

The way I approach is correct or is there any other way to do it?

Any help would be much appreciated.

Updated

_locationSubscription = location.onLocationChanged().listen((newData) {

  const oneSec = const Duration(seconds: 5);
  new Timer.periodic(oneSec, (Timer t) {

    print(newData.latitude);

    mapController.animateCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
          target: LatLng(newData.latitude, newData.longitude), 
          zoom: 17.0
        )
      )
    );

    updateToDb(newData);

  });

});

Solution

  • As per the package's documentation, interval only works on Android, so you should design your own logic for how often to update the map, for example using Timer.periodic.

    Also, changeSettings is a Future, so your current code is likely to start listening for location changes before the settings are applied. You should await the call to changeSettings.