Search code examples
flutterbackgroundlocation

How to use callback in flutter for background location


I am following this plugin (learning) background locator . I have previously used other background location plugins but they are not maintained anymore.

I am following the tutorial as described in the description of the plugin and so far this is my code. I am unsure about what exactly a callback is and how do I use it.

This is my code so far but I don't get any results.

static void backgroundLocationCallBack(LocationDto location) async {
    await BackgroundLocator.initialize();
    await BackgroundLocator.isServiceRunning();
  }

  void getLocationLiveUpdates() async {
    return await BackgroundLocator.registerLocationUpdate(
        backgroundLocationCallBack,
        autoStop: false,
        // disposeCallback: backgroundLocationDisposeCallBack,

        androidSettings: AndroidSettings(
            accuracy: LocationAccuracy.NAVIGATION,
            interval: 5,
            distanceFilter: 0,
            client: LocationClient.google,
            androidNotificationSettings: AndroidNotificationSettings(
              notificationChannelName: 'Location tracking',
              notificationTitle: 'Start Location Tracking',
              notificationMsg: 'Track location in background',
              notificationBigMsg:
                  'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
              notificationIconColor: Colors.grey,
            )));
  }

Solution

  • Callbacks are used to perform some actions during certain events.

    Here, the callback attribute takes backgroundLocationCallBack as its value, and as per the package code, it is used for performing appropriate actions when the LocationDto is available. This LocationDto object will contain the Location information you are looking for, and you can use it according to your use-case.

    Similarly, disposeCallback is used to perform certain actions when dispose is called on the BackgroundLocator object. You can do something like close all the Ports that were opened for fetching the location.

    There are other callbacks as well such as initCallback and initDataCallback which are used for setting the callbacks to initialise various parameters for your location service and to provide an initial data for the params respectively.