Search code examples
iosfluttergeolocationbackground-service

Background service issue : App crush when using geolocator


I'm working on a fitness/health flutter app project.

My app work just works fine on android, but the app crashes and stops working immediately in ios when I'm invoking location service.

I have a button inside a map view page to start counting steps and time of the walking sessions.

My button's code

  RaisedButton(
                          textColor: Colors.white,
                          color: checkRun == false
                              ? Settings.mainColor()
                              : Colors.red,
                          child: Container(
                              padding: EdgeInsets.all(15),
                              child: checkRun == false
                                  ? Text(allTranslations.text("startNow"))
                                  : Text(allTranslations.text("endNow"))),
                          onPressed: () async {
                            rightButtonPressed();
                            if (checkRun == false) {
                              getLocation();
                            } else if (checkRun == true) {
                              setState(() {
                                checkRun = false;
                              });
                              try {
                                FormData formdata = new FormData();
                                // get user token
                                SharedPreferences sharedPreferences =
                                    await SharedPreferences.getInstance();
                                Map<String, dynamic> authUser = jsonDecode(
                                    sharedPreferences
                                        .getString("authUser"));
                                dio.options.headers = {
                                  "Authorization":
                                      "Bearer ${authUser['authToken']}",
                                };
                                formdata.add("startLongitude",
                                    points.first.longitude);
                                formdata.add(
                                    "endLongitude", points.last.longitude);
                                formdata.add(
                                    "startLatitude", points.first.latitude);
                                formdata.add(
                                    "endLatitude", points.last.latitude);
                                formdata.add("date", DateTime.now());

                                meter = distance.as(
                                    lm.LengthUnit.Meter,
                                    lm.LatLng(points.first.latitude,
                                        points.first.longitude),
                                    lm.LatLng(points.last.latitude,
                                        points.last.longitude));
                                setState(() {});

                                print(meter);

                                formdata.add("distance", meter.toInt());
                                formdata.add("steps", _polylineIdCounter);
                                formdata.add("calories", (_polylineIdCounter*0.0512).toInt());

                                response = await dio.post(
                                    "http://104.248.168.117/api/mapInformation",
                                    data: formdata);
                                if (response.statusCode != 200 &&
                                    response.statusCode != 201) {
                                  return false;
                                } else {
                                  print('success -->');
                                  print('Response = ${response.data}');
                                  return true;
                                }
                              } on DioError catch (e) {

                                return false;
                              }
                            }
                           // return true;
                          },
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20.0)))

getLoaction code :

 getLocation() {
setState(() {
  checkRun = true;
});
print('CheckRun = > $checkRun');
// Fired whenever a location is recorded
bg.BackgroundGeolocation.onLocation((bg.Location location) {
  print('[location] - $location');
  print('<--------- start onLocation -----------> ');
  print(location.coords.latitude);
  print(location.coords.longitude);
  print('<--------- End onLocation -----------> ');
  if (checkRun == true) {
    setState(() {
      points.add(_createLatLng(
          location.coords.latitude, location.coords.longitude));
      print('Points=> $points');
      _add();
    });
  } else if (checkRun == false) {
    setState(() {
      points.clear();
    });
  }
});

// Fired whenever the plugin changes motion-state (stationary->moving and vice-versa)
bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
  print('[motionchange] - $location');
  print('<--------- Locaiton onMotionChange -----------> ');
  updatelat=location.coords.latitude;
  updatelong=location.coords.longitude;
  setState(() {

  });
  print(location.coords.latitude);
  print(location.coords.longitude);
  print('<--------- / Locaiton onMotionChange -----------> ');
});

// Fired whenever the state of location-services changes.  Always fired at boot
bg.BackgroundGeolocation.onProviderChange((bg.ProviderChangeEvent event) {
});

////
// 2.  Configure the plugin
//
bg.BackgroundGeolocation.ready(bg.Config(
        desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
        distanceFilter: 10.0,
        stopOnTerminate: false,
        startOnBoot: true,
        debug: false,
        logLevel: bg.Config.LOG_LEVEL_INFO,
        reset: true))
    .then((bg.State state) {
  if (!state.enabled) {
    ////
    // 3.  Start the plugin.
    //
    print('[ready] success: $state');
    bg.BackgroundGeolocation.start();
  }
});}

I'm using these packages:

  flutter_background_geolocation: ^1.2.4
    geolocator: ^5.0.1

Solution

  • Map view is crushing in the release version because flutter_background_geolocation is required you to buy a license to make it work in release versions, so it will work fine with you when you build the app in debug mode but it will crush on release mode without a license.