Flutter: Run code in the background
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…