2

I want to update user's location in background.

To perform tasks in background, i used this package, workmanager. Link to that: https://pub.dev/packages/workmanager

But i can not update the location, it seems like it can't work with async code?

here is my code,

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    await _HomeScreenState().updateUserLoc();
    print('it is working?');

    return Future.value(true);
  });
}
//Inside my stateFul Widget,



 void initState() {
    super.initState();
  
    
    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: true,
    );

    Workmanager.registerPeriodicTask(
      "1",
      fetchBackground,
      frequency: Duration(minutes: 15),
    );
  }


updateUserLoc() async {
    print("executi9ng the updateUserLocccccc");
    await getusersLocation();
    print("executi9ng the updateUserLoc");
    GeoFirePoint point = geo.point(latitude: lat, longitude: long);
    _firestore.collection('locations').document(widget.userid).setData(
      {'position': point.data},
      merge: true,
    );
  }

Is there any other way of updating the users's location in background?

Samuel Romero
  • 1,233
  • 7
  • 12
Madhavam Shahi
  • 1,166
  • 6
  • 17

1 Answers1

1

You have to call the call the code inside the updateUserLoc() directly inside the callbackDispatcher. Just make the callbackDispatcher async function.

Szepetry
  • 52
  • 4
  • But, to make that work, I'll have to move much of my code above the class(..making it top level), would that be a good practice? – Madhavam Shahi Aug 13 '20 at 04:40
  • You could make the callbackDIspatcher function itself inside the class you wanted to put the updateUserLoc(). Keep in mind to make it the top level function and import the file ito the file where you're calling workmanager.initialize. – Szepetry Aug 13 '20 at 14:05
  • How I like to use workmanager callbackDispatchers is by creating a separate background services class and I keep all similar functions in that file. – Szepetry Aug 13 '20 at 14:07