Flutter 取消地理定位器侦听器

spo*_*oss 3 geolocation dart flutter

我正在使用 Geolocator 库来检测用户的位置。但是,它运行良好,当请求位置更新的特定屏幕关闭时,我希望侦听器停止接收任何更新。我不知道如何实现这一目标。这是我的代码

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();
  }

}
Run Code Online (Sandbox Code Playgroud)

我尝试在 dispose 方法中取消监听器,但监听器仍然存在。

Gün*_*uer 8

  StreamSubscription _getPositionSubscription;
  _getLocation(){
    _getPositionSubscription = geolocator.getPositionStream(locationOptions).listen(
    ...
  }

  @override
  void dispose() {
    _getPositionSubscription?.cancel();
    super.dispose();
  }
Run Code Online (Sandbox Code Playgroud)