Madhavam Shahi
Madhavam Shahi

Reputation: 1192

Async function not working in WorkManager

I am using a package WorkManager to perform some background tasks.(updating user's location). https://pub.dev/packages/workmanager

Here is my top level function.

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    _HomeScreenState().updateUserLoc();

    return Future.value(true);
  });
}

Here is my initstate, where i initialised the workmanager.

void initState() {
    super.initState();

    
    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: true,
    );

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

here is my updateUserLoc() function.

updateUserLoc() async {
    await GetusersLocation();

    GeoFirePoint point = geo.point(latitude: lat, longitude: long);
    _firestore.collection('locations').document(widget.userid).setData(
      {'position': point.data},
      merge: true, 
    );

    print("executing the updateUserLoc");
  }

This does not work,

when i place "print("executing the updateUserLoc");" just below the function, it gets printed, but when below, it does not.

What am i doing wrong here. please help.

Upvotes: 4

Views: 732

Answers (1)

nvoigt
nvoigt

Reputation: 77364

You need to properly await your futures:

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    await _HomeScreenState().updateUserLoc();

    return true;
  });
}

Upvotes: 3

Related Questions