flutter-mapbox-gl / maps

A Mapbox GL flutter package for creating custom maps
Other
1.04k stars 503 forks source link

onLocationchange.listen((event){}) enter into loop flutter #1307

Closed milad-alsabbagh closed 1 year ago

milad-alsabbagh commented 1 year ago

I have this function in flutter to calculate distance between particular geometry point and user loaction when user start moving any way every thing goes right but I want to make function take new values even if the the user doesn't arrive to distance so that I want to stop the onLocationChange on old values but I can't make cancel() from outside the listen itself this is my code calculateDistance(String? taskname,LatLng tasklatlong,bool start)async { FirebaseFirestore.instance .collection("tasks") .doc(empname) .collection("tasks") .doc(taskname) .update({ 'start time': DateTime.now().toString().substring(10, 16), 'estimated time ': double.parse((duration / 60).toStringAsFixed(2)) });

locationsubscription =
    locationChange.onLocationChanged.listen((event) async {
      if(start==false){
      locationsubscription?.cancel();}
      else{
      await CacheHelper.sharedPreferences!.reload();
     locationChange.enableBackgroundMode(enable: true);
  print('after initilize');
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(event.latitude!-tasklatlong.latitude);  // deg2rad below
  var dLon = deg2rad(event.longitude!-tasklatlong.longitude);
  var a =
      sin(dLat/2) * sin(dLat/2) +
          cos(deg2rad(event.latitude)) * cos(deg2rad(tasklatlong.latitude)) *
              sin(dLon/2) * sin(dLon/2);
  var c = 2 *atan2(sqrt(a), sqrt(1-a));
  var d = R * c*1000; // Distance in km
  print('distance is $d');
  if (d <= 50) {
    print('arrived to location');
    FirebaseFirestore.instance
        .collection("tasks")
        .doc(empname)
        .collection("tasks")
        .doc(taskname)
        .update(
            {'arrived time': DateTime.now().toString().substring(10, 16)});
    Fluttertoast.showToast(
        msg: 'You arrived to location', backgroundColor: approvecolor);
    locationsubscription?.cancel();
    setState(() {
      myLocationEnabled=false;
    });
    calculateWastedTime();
  }
  else {
    print('not arrived ');
  }}
});

} how can I use locationsubscription.cancel() from outside the function I tried to use it but it just still in the loop until it cancel from inside

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.