Updated 27 April 2023
In this article we will learn how to use work manager in flutter. Before starting its implementation we will discuss work manager in brief.
Work manager is useful for creating periodic jobs in background that require the system to guarantee that they will be completed even if the app is closed.
WorkManager does the heavy lifting for you, taking care of compatibility concerns and battery and system health best practises.
You may also schedule both periodic jobs and sophisticated dependent chains of tasks with work manager, background work can be conducted in parallel or sequentially, with an execution order specified. WorkManager in flutter manages the flow of input and output between tasks with ease.
 You may also check our Flutter app development services page.
1. Project setup
Create a new flutter project and add latest workmanager version under dependecies in pubspec.yaml file of your project as following example and run flutter pub get command to install this library in your project.
1 2 3 |
dependencies: workmanager: ^0.4.1 |
2. Import package
Add following line in your class to import the package.
1 |
<strong>import</strong> 'package:workmanager/workmanager.dart'; |
3. Implementation
Now you can use following code to register periodic task.
1 2 3 4 5 6 7 8 9 |
ElevatedButton( child: Text("Register Periodic Task"), onPressed: () { Workmanager().registerPeriodicTask( "3", simplePeriodicTask, initialDelay: Duration(seconds: 10), ); }), |
It will wait at least 10 seconds before its first launch.
Since we have not provided a frequency it will be the default 15 minutes.
4. Example
Use following code as example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
import 'dart:async'; import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:workmanager/workmanager.dart'; void main() => runApp(MyApp()); const simpleTaskKey = "simpleTask"; const rescheduledTaskKey = "rescheduledTask"; const failedTaskKey = "failedTask"; const simpleDelayedTask = "simpleDelayedTask"; const simplePeriodicTask = "simplePeriodicTask"; const simplePeriodic1HourTask = "simplePeriodic1HourTask"; void callbackDispatcher() { Workmanager().executeTask((task, inputData) async { switch (task) { case simpleTaskKey: print("$simpleTaskKey was executed. inputData = $inputData"); final prefs = await SharedPreferences.getInstance(); prefs.setBool("test", true); print("Bool from prefs: ${prefs.getBool("test")}"); break; case rescheduledTaskKey: final key = inputData!['key']!; final prefs = await SharedPreferences.getInstance(); if (prefs.containsKey('unique-$key')) { print('has been running before, task is successful'); return true; } else { await prefs.setBool('unique-$key', true); print('reschedule task'); return false; } case failedTaskKey: print('failed task'); return Future.error('failed'); case simpleDelayedTask: print("$simpleDelayedTask was executed"); break; case simplePeriodicTask: print("$simplePeriodicTask was executed"); break; case simplePeriodic1HourTask: print("$simplePeriodic1HourTask was executed"); break; case Workmanager.iOSBackgroundTask: print("The iOS background fetch was triggered"); Directory? tempDir = await getTemporaryDirectory(); String? tempPath = tempDir.path; print( "You can access other plugins in the background, for example Directory.getTemporaryDirectory(): $tempPath"); break; } return Future.value(true); }); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } enum _Platform { android, ios } class PlatformEnabledButton extends ElevatedButton { final _Platform platform; PlatformEnabledButton({ required this.platform, required Widget child, required VoidCallback onPressed, }) : super( child: child, onPressed: (Platform.isAndroid && platform == _Platform.android || Platform.isIOS && platform == _Platform.ios) ? onPressed : null); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Flutter WorkManager Example"), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text("Plugin initialization", style: Theme.of(context).textTheme.headline4), ElevatedButton( child: Text("Start the Flutter background service"), onPressed: () { Workmanager().initialize( callbackDispatcher, isInDebugMode: true, ); }), SizedBox(height: 16), Text("One Off Tasks (Android only)", style: Theme.of(context).textTheme.headline4), //This task runs once. //Most likely this will trigger immediately PlatformEnabledButton( platform: _Platform.android, child: Text("Register OneOff Task"), onPressed: () { Workmanager().registerOneOffTask( "1", simpleTaskKey, inputData: <String, dynamic>{ 'int': 1, 'bool': true, 'double': 1.0, 'string': 'string', 'array': [1, 2, 3], }, ); }, ), PlatformEnabledButton( platform: _Platform.android, child: Text("Register rescheduled Task"), onPressed: () { Workmanager().registerOneOffTask( "1-rescheduled", rescheduledTaskKey, inputData: <String, dynamic>{ 'key': Random().nextInt(64000), }, ); }, ), PlatformEnabledButton( platform: _Platform.android, child: Text("Register failed Task"), onPressed: () { Workmanager().registerOneOffTask( "1-failed", failedTaskKey, ); }, ), //This task runs once //This wait at least 10 seconds before running PlatformEnabledButton( platform: _Platform.android, child: Text("Register Delayed OneOff Task"), onPressed: () { Workmanager().registerOneOffTask( "2", simpleDelayedTask, initialDelay: Duration(seconds: 10), ); }), SizedBox(height: 8), Text("Periodic Tasks (Android only)", style: Theme.of(context).textTheme.headline4), //This task runs periodically //It will wait at least 10 seconds before its first launch //Since we have not provided a frequency it will be the default 15 minutes PlatformEnabledButton( platform: _Platform.android, child: Text("Register Periodic Task"), onPressed: () { Workmanager().registerPeriodicTask( "3", simplePeriodicTask, initialDelay: Duration(seconds: 10), ); }), //This task runs periodically //It will run about every hour PlatformEnabledButton( platform: _Platform.android, child: Text("Register 1 hour Periodic Task"), onPressed: () { Workmanager().registerPeriodicTask( "5", simplePeriodic1HourTask, frequency: Duration(hours: 1), ); }), ], ), ), ), ); } } |
5. Dispose a work manager
You can dispose a work manager by using following ways.
i) By using unique name
1 |
Workmanager().cancelByUniqueName("<MyTask>"); |
ii) By using tag
1 |
Workmanager().cancelByTag("tag"); |
6. Dispose all work manager jobs
Once the scheduled jobs are done, close all the workmanagers you’ve called by using following code.
1 2 3 4 5 6 7 |
ElevatedButton( child: Text("Cancel All"), onPressed: () async { await Workmanager().cancelAll(); print('Cancel all tasks completed'); }, ), |
It will stop all your work managers.
In this article, we have learned about use of work manager in flutter using workmanager plugin.
Thanks for reading the blog. For more such amazing articles on latest trends in mobile application development, please visit our mobikul blog site.
Happy coding 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.