Run your code in the background even if the app is closed in Flutter App

Run your code in the background

Hi, everyone this post will discuss how we can run our code in the background. And you will learn how to set a background task for one time or for periodic means your function will run in an interval. If you are a flutter developer then in development there are some situations when you want your code to run in the background to do specific tasks.

You can take the example of an app where some data on the server is changed and you want the app to get the latest data as that data is very important for your user to know. So we can write a code or function that will work in the background and that code will execute even if the app is not in the foreground or the app is closed. 

To implement this functionality first you have to understand what is a background task in android. According to developer.android.com, the definition of background work or task is: An app is running in the background when both the following conditions are satisfied: None of the app’s activities are currently visible to the user. The app isn’t running any foreground services that started while activity from the app was visible to the user.

You can take an example of whats app. This app uses a background task to backup your messages and upload it to the server and this doesn’t need any user interaction. Now I hope you got an idea of what a background task is.

Enough talking let’s code: 

Step1 :

So for implementing the background task in our flutter app we will use Flutter Workmanager package which is wrapper around Android WorkManager, iOS’ performFetchWithCompletionHandler and iOS BGAppRefresh Task. this package allow our code to execute headlessly. 

Using this package is not to hard we just have to set it up for android and iOS 

For android make some changes in you build.gradle from project level file
Make sure that your kotlin_version is 1.5.0` or greater:

buildscript {
    ext.kotlin_version = '1.5.+'
    repositories {
        google()
        mavenCentral()
    }

Check your AndroidManifest.xml file.

<meta-data
    android:name="flutterEmbedding"
    android:value="2" />

For setting on iOS you can refer to this site

Now create a new flutter project name it whatever you want. We will configure all our code in main.dart file so please follow along.

Add the dependency in your pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  workmanager: ^0.5.0

Or you can run the command in cmd while you are in your project 

flutter pub add workmanager

Step2:

To initialize work manager first we have call flutters insure initialize function like this 

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

Make sure you call before runApp function. 

Now lets initialize workmanger for this we use Workmanager().initialize(your_function_name) like this.

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(callbackDispatcher);
  runApp(const MyApp());
}

This workmanager initialize takes a callback function as a parameter and this can be a local function and can be a global function we will use a global function. Define a global callback function as we define here

void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    // your code that you want to run in background
    print('Task executed: '+ taskName);
    return Future.value(true);
  });
}

This function is doing nothing but printing some string. For executing this function we will use initstate as follow

  @override
  void initState() {
    super.initState();
    Workmanager().registerOneOffTask('taskName', 'backUpData');
  }

This Workmanager().registerOneOffTask has some more property that is self explainable you can figurer out it’s working by looking at it but for now just write as i wrote in the code this line of code will call our function that we define as a global function earlier. It will be execute immediately as the app is launched but if you want some delay you can add like this

  @override
  void initState() {
    super.initState();
    Workmanager().registerOneOffTask(
      'taskName',
      'backUpData',
      initialDelay: Duration(seconds: 5),
    );
  }

I hope you understand this now we will look for periodic background task. We will also implement it inside initstate as follow.

void initState() {
    Workmanager().registerPeriodicTask('uniqueName', 'taskName',
        frequency: Duration(hours: 1));
    super.initState();
  }

The first parameter is unique name it has to be unique if you have multiple task to perform because later if you want to cancel this background task you can cancel it by its unique name. The second parameter is task name it the name of your task and the frequency property is the time gap. The callback function will run after the time gap.

By default the gap or the frequency of time interval is 15 minutes. You can perform task after every 15 minutes. If you define time less then 15 minutes the android system will make it to 15.

Full Code:

main.dart file

import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
 
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    // your code that you want to run in background
    print('#' * 200);
    print('Executing task');
    Future.delayed(Duration(seconds: 4));
    print('Task executed: ' + taskName);
    return Future.value(true);
  });
}
 
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(callbackDispatcher);
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}
 
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
 
  @override
  State<HomePage> createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Background taks'),
      ),
      body: Container(),
    );
  }
 
  // @override
  // void initState() {
  //   super.initState();
  //   Workmanager().registerOneOffTask(
  //     'taskName',
  //     'backUpData',
  //     initialDelay: Duration(seconds: 5),
  //   );
  // }
 
  @override
  void initState() {
    Workmanager().registerPeriodicTask('uniqueName', 'taskName',
        frequency: Duration(hours: 1));
    super.initState();
  }
}

Thankyou for reading!

I hope now you can implement background task in your app very easily if you have any doubt then feel free to comment.


For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

1 thought on “Run your code in the background even if the app is closed in Flutter App”

  1. Hello brother, I saw your code is shown but I need to ask more questions here. I need to use Workmanager for running always my all functions in the foreground and keep the app view like before we terminate app after we go again to the foreground, How about your idea? Thank you, brother.

    Reply

Leave a Comment