Run Flutter App in background(Terminated state)

Siddharth Khore
2 min readMar 26, 2021

--

Flutter has a stunning plugin named “background_fetch” which allows you to run your code when app is in terminated state & background state.

**7 easy steps to Execute your flutter code when app is in background.**

  • Declare the callback function(headlessTaskFunction) in main.
  • Configure the background_fetch in initState().
  • Write the code in callbackFunction you want to perform in background.
  • Schedule minimumFetchInterval (minimum 15 min)
These are headless events of background fetch

1. Dependency plugin:
Add this plugin to your pubspec.yaml file.

background_fetch: ^0.7.1

2. Import it:

import ‘package:background_fetch/background_fetch.dart’;

3. Setup:

4. Register headless task in main:

void main(){
runApp(new app());
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}

5. Add configuration for background fetch events:

BackgroundFetch.start().then((int status) {
print(‘[BackgroundFetch] start success: $status’);
}).catchError((e) {
print(‘[BackgroundFetch] start FAILURE: $e’);
});

// Configure BackgroundFetch.

BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15, // should be 15<=minimumFetchInterval
forceAlarmManager: false,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.NONE,
), _onBackgroundFetch).then((int status) {
print(‘[BackgroundFetch] configure success: $status’);
}).catchError((e) {
print(‘[BackgroundFetch] configure ERROR: $e’);
});

6. Add _onBackgroundFetch function: (function which will execute in foreground).

void _onBackgroundFetch(String taskId) async {
BackgroundFetch.finish(taskId);
}

7. Add backgroundFetchHeadlessTask function: (This “Headless function” will run when app is in terminated state).

void backgroundFetchHeadlessTask(String taskId) {
// Evaluate all the tasks which you want to perform in
terminated state.
// write the code to be run in background
BackgroundFetch.finish(taskId);
}

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

--

--