我正在使用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();
}
}
我尝试在dispose方法中取消侦听器,但侦听器仍然存在。
答案 0 :(得分:3)
StreamSubscription _getPositionSubscription;
_getLocation(){
_getPositionSubscription = geolocator.getPositionStream(locationOptions).listen(
...
}
@override
void dispose() {
_getPositionSubscription?.cancel();
super.dispose();
}