Flutter Cancel Geolocator Listener

I am using Geolocator library to detect the location of the user. It works well however, I would like the listener to stop receiving any updates when the particular screen requesting the location updates is closed. I have no idea how to achieve this. Here is my code

class _CheckLoactionScreenState extends State<CheckLocationScreen>{
  String _geoHash = "No Geo Hash";
  String _placeId = "No Place Detected";
  String _coordinates = "";
  var geolocator = Geolocator();
  var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _body(),
    );
  }

  _body(){
    return Center(
      child: Text(_geoHash),
      ),
    );

  }

  _getLocation(){
    geolocator.getPositionStream(locationOptions).listen(
            (Position position) {
              //print("${position.toString()}");
              var newGeoHash = Geohash.encode(position.latitude, position.longitude).substring(0,8);
              if(newGeoHash != _geoHash){
                  setState((){
                    _geoHash = newGeoHash;
                    });                
              }
              _coordinates = position.toString();
              print(_geoHash);
        });
  }


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

  @override
  void dispose() {
    print("**** dispose");
    geolocator.getPositionStream(null).listen(null);
    super.dispose();
  }

}

I attempt to cancel the listener in the dispose method but the listener still persists.

1 answer

  • answered 2018-10-09 16:30 Günter Zöchbauer

      StreamSubscription _getPositionSubscription;
      _getLocation(){
        _getPositionSubscription = geolocator.getPositionStream(locationOptions).listen(
        ...
      }
    
      @override
      void dispose() {
        _getPositionSubscription?.cancel();
        super.dispose();
      }