Reputation: 81
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?
Upvotes: 7
Views: 7151
Reputation: 472
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.
Upvotes: 23