Flutter: Run code in the background

KNNX Corp.
KNNX Corp.
Published in
4 min readJan 19, 2022

--

Today, I will explain how to create a background task in Flutter.

Before that, let us understand what a background task is. A background task is a worker process of an application that runs in the background, even if the application is not running or is in a terminated state.

This feature can be beneficial in applications that need to perform tasks in the background without asking the user to open the app — for example, calling the APIs to get data every 15 minutes.

Let us implement a background task in an example project to understand the implications of this in action better.

We start by completing the following steps:

  • Add the package ‘background_fetch’ in pubspec.yaml and run the ‘flutter pub get’ command in the terminal.
  • Import the background package in the main.dart file and register the ‘HeadlessTask’ to receive ‘backgroundFetch’ events after the app is terminated.

For Example:

void backgroundFetchHeadlessTask(HeadlessTask task) async {var taskId = task.taskId;
if(taskId == ‘your_task_id’) {
print(‘your_task_id’);
print(‘[BackgroundFetch] Headless event received.’);
//TODO: perform tasks like — call api, DB and local notification etc…
}
}
void main() {
runApp(MyApp());
//Registering backgroundFetch

--

--

KNNX Corp.
KNNX Corp.

KNNX is a global leader in Distributed Ledger Technology and Enterprise Products. To learn more, head over to: https://www.knnx.com/