Flutter background job
Do you want to run dart code in the background? And get the data from the server and want to show that to the user when the user opens the app. If Yes let’s go to explore this first we will learn how we can run background tasks. I knew when the first time you tried to run a background task you failed like me and said to yourself it’s kinda frustrating work but hey it’s not it’s really amazing when I explore it.
Suppose you are building new app and the app consist with multiple scenarios
- Headlines
- Recent news
- Popular news
And so on. Lemme tell you one more interesting thing, we are living in a world where we want everything very quickly like (The Flash superhero of television series developed by Greg Berlenti) When users open the app . Users quickly want to get the latest news about what’s going on in the country. So how can we do this? Simple answer: We will set up a background job which periodically fetches the latest articles.
Before start hunting of background job I want to tell you briefly about Native Android and iOS
Android
On Android We have multiple ways to schedule background jobs. Or we can say we have free hands to schedule background jobs and every year we see something new in android.
Right Now we have available options in android to schedule background jobs are
- AlarmManager
- JobService
- Firebase Job Dispatcher
- WorkManager
I’m not going to touch the depth of these all but I can tell you a short interesting story about the latest background job scheduler Workmanager. WorkManager provides an easy to use Api Where we can easily define background job once or periodically.
The job is guaranteed to run some time in the future. One more interesting thing Android Takes full ownership of when is the best time to run background jobs, and batches these jobs
iOS
As we know On iOS we have not that many options. The system decides when to give an app the chance to perform background fetch. We have the only control minimum background fetch interval.
Okay sounds good it’s time to start digging with flutter and run background jobs but question arises how?
Hey if you have the same question like I had How? It means we are on the track. Let’s figure things out.
The first thing first as Stephen Covey Said in has book 7 habits of effective people
- We first start flutter engine in the background
question : can Android/iOS start the flutter engine in the background?
Yes! Of course first we need to register a dart callback function which will only be invoked whenever a background job is started by the native code.
But this is not our headache anymore in the flutter we are in 2022. We have an amazing plugin WorkManager which makes our life easier. We don’t need to write boilerplate code. WorkManager manages everything for us.
Short Note: WorkManager plugin will only work on Android & iOS.
Let’s Go and build a small app so we can understand better.
Always Remeber practice makes a man perfect.
Step 1:
Add WorkManager in your pubspec.yamal file right now WorkManager latest version is : workmanager: ^0.5.0
If you are reading this article in the future , I hope this 0.5.0 version will be updated.
Step 2:
Platform setup
Android
Update build.gradle
Get Muhammad Aamir’s stories in your inbox
Join Medium for free to get updates from this writer.
Make sure that your kotlin_version to 1.5.0` or greater
buildscript {ext.kotlin_version = ‘1.5.+’repositories {google()mavenCentral()}
Check your AndroidManifest.xml
Check if you have the following in your AndroidManifest.xml file.
<meta-dataandroid:name="flutterEmbedding"android:value="2" />
Ideally you should have this
iOS Installation
This plugin is compatible with Swift 4.2 or above. Make sure you are using Xcode 10.3 or higher and have set your minimum deployment target to iOS 10 or higher by defining a platform version in your podfile: platform :ios, ‘10.0’
This will add the UIBackgroundModes key to your project’s Info.plist:
<key>UIBackgroundModes</key><array><string>processing</string></array>
For more information please read this (link)
How to use the package?
Before registering any task, the WorkManager plugin must be initialized
const myBackgroundJob = "myBackgroundJob";void main() {Workmanager().initialize(callbackDispatcher);
Workmanager().registerOneOffTask("1", myBackgroundJob, //This is the value that will be returned in the callbackDispatcher
initialDelay: Duration(seconds: 30),
constraints: Constraints(
networkType: NetworkType.connected,
requiresCharging: true,
));runApp(MyApp());}void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) {
switch (taskName) {
case myBackgroundJob:
print("this method was called from native!");
break;
case Workmanager.iOSBackgroundTask:
print("iOS background fetch delegate ran");
break;
}
//Return true when the task executed successfully or not
return Future.value(true);
});
}
With the help of the registerOneOffTask we tell Flutter explicitly to start an Android job.
The value of myBackgroundJob variable will be returned to the registered callbackDispatcher so you can differentiate if you have multiple tasks.
iOS’ performFetch will always return a fixed value of Workmanager.iOSBackgroundTask .
I’ll see you in the next article where we will build complete app using WorkManager hope you find something valuable
Thanks For reading.
Follow Me on Social Media for more amazing content:
GitHub: https://github.com/amirk3321
LinkedIn: https://www.linkedin.com/in/muhammad-amir-119542b3
Website: https://www.etechviral.com
YouTube: https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A
eTechViral Instagram: https://www.instagram.com/etechviral/







