What is workmanager?
- Flutter course
- Advanced
- Lesson 41/69
- 4 min
Schedule background jobs with workmanager.
What is workmanager?
The workmanager package is used to schedule background tasks that run even when the app is closed. It is initialized with Workmanager().initialize and tasks are registered. The package wraps the WorkManager API on Android and the BGTaskScheduler API on iOS.
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);Workmanager initialization
Before using Workmanager you call the initialize method. Its first parameter is the background callback, callbackDispatcher. This call is made in the app's main function and runs only once.
void main() {
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
}Practice Initialize Workmanager
Define a callbackDispatcher function (takes task as parameter, returns true). In main call Workmanager().initialize and print 'ok'.
Starter code
class Workmanager {
void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
}
// callbackDispatcher fonksiyonunu yaz
// task parametresi alsın, true döndürsün
void main() {
// Workmanager'ı başlat
// 'ok' yazdır
}Sample solution
class Workmanager {
void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
}
bool callbackDispatcher(String task) {
return true;
}
void main() {
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
print('ok');
}Expected output
ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the workmanager package provide?
- Drawing the user interface
- Speeding up database queries
- Running animations in the foreground
- Scheduling background tasks while the app is closed Correct answer
Explanation: workmanager schedules background tasks that can run even when the app is closed; it has nothing to do with animations, UI drawing, or database speedups.
2 Initialize Workmanager
Workmanager().____(callbackDispatcher, isInDebugMode: true);
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
Explanation: To initialize Workmanager you call the initialize method; its first parameter is the callbackDispatcher function.
3 workmanager parts
| Term | Meaning |
|---|---|
Workmanager |
Background task package |
initialize |
Initialization method |
callbackDispatcher |
Background callback |
background |
Background |