6

I am using Location plugin to get user's current location. It is working fine.

But I need to stop location listening when user close the current page.

listenLocation=  (LocationData locationData) async {
      if (mounted) {
        setState(() {
          userLocation = locationData;
        });
      }
      print("lat: " +
          userLocation.latitude.toString() +
          " - Long: " +
          userLocation.longitude.toString());
    };
    location.onLocationChanged().listen(listenLocation);

How can I stop listening in dispose method?

1 Answer 1

20

I was looking for an answer for this aswel turns out you need to do the following.

import 'dart:async';

StreamSubscription<LocationData> locationSubscription;

locationSubscription = location.onLocationChanged().listen((LocationData currentLocation)
{
  //Your code
});

Then to stop it call

locationSubscription.cancel();

And if you want to resume where you left off call

locationSubscription.resume();

Hope it will help someone else out who actually wants to stop background listeners and not just keep them running since it's no where in the docs of the package.

2
  • 1
    this is worked, thanks. btw, where is the best place to put locationSubscription = location.onLocationChanged().listen Sep 1, 2020 at 14:28
  • you need locationSubscription.pause(); if you want to use locationSubscription.resume();
    – Simon Fry
    Aug 17, 2022 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.