close
0

How to schedule background tasks in Flutter?

avatar
asked 13-09-2021

3 Answers


0
//Provide a top level function or static function.
//This function will be called by Android and will return the value you provided when you registered the task.
//See below
void callbackDispatcher() {
  Workmanager.executeTask((task) {
    print("Native echoed: $task");
    return Future.value(true);
  });
}

Workmanager.initialize(
    callbackDispatcher, //the top level function.
    isInDebugMode: true //If enabled it will post a notification whenever the job is running. Handy for debugging jobs
)
avatar
answered 14-09-2021

0

Use WorkManager library

dependencies:
  workmanager: ^0.2.3

WorkManager comes under two parts, which run the task in the background.

1. Delayed background work

registerOneOffTask runs the task only once with an initial delay of 10 seconds. This is useful when we need to perform any background work only once.

Example:

Workmanager.registerOneOffTask(
  "1",
  "registerOneOffTask",
  initialDelay: Duration(seconds: 10),
);

avatar
answered 14-09-2021

0

Periodic background work

This task runs periodically, Since we have not provided a frequency it will be the default 15 minutes. Example:

Workmanager.registerPeriodicTask(
  "2",
  "registerPeriodicTask",
  initialDelay: Duration(seconds: 10),
);
avatar
answered 14-09-2021