The original

www.dltlabs.com/blog/flutte…

reference

  • Pub. Dev/packages/ba…

The body of the

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

Before we do that, let’s understand what a background task is. A background task is a helper process for an application running in the background, even if the application is not running or in a terminated state.

This feature is beneficial for applications that need to perform tasks in the background without requiring the user to open the application, for example, calling the API every 15 minutes to get data.

Let’s implement a background task in a sample project to better understand what this means.

Steps:

  • pubspec.yaml
flutter pub add background_fetch
flutter pub get
Copy the code
  • Import the background package in the main.dart file and register HeadlessTask to receive backgroundFetch events after the application terminates.

Such as:

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 to receive events after app is terminated.
// Requires {stopOnTerminate: false, enableHeadless: true}
_BackgroundFetch._registerHeadlessTask_(backgroundFetchHeadlessTask);
}
Copy the code

Here we have to pass a top-level function. Let’s name it Call Back Dispatcher in the registerHeadlessTask method. Then we define the tasks that need to run in the background:

Configuration BackgroundFetch

Future<void> initPlatformState() async{_// Configure BackgroundFetch.
_var status = await BackgroundFetch._configure_(BackgroundFetchConfig(
minimumFetchInterval: 15,
forceAlarmManager: false,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.NONE,
), _onBackgroundFetch, _onBackgroundFetchTimeout);
print(' [BackgroundFetch] configure success: $status "); _// Schedule backgroundfetch for the 1st time it will execute with 1000ms delay.
// where device must be powered (and delay will be throttled by the OS)._BackgroundFetch. ScheduleTask (TaskConfig: (taskId "com. Dltlabs. Task", the delay:1000,
periodic: false,
stopOnTerminate: false,
enableHeadless: true
));
}
Copy the code

Call the initPlatformState method in initState and set the configuration of the BackgroundFetchConfig class. In other words, provide the option to register one-time or periodic tasks while passing other parameters.

Here, if there are multiple tasks, the task ID helps us easily identify the individual task. The input data can be any information needed to process the task.

If we want to continue working while the application is terminated, set the stopOnTerminate parameter to false. If stopOnTerminate is set to true, the background service terminates when the application terminates.

void _onBackgroundFetchTimeout(String taskId) {
print(" [BackgroundFetch] a TIMEOUT: $taskId "); BackgroundFetch.finish(taskId); }Copy the code

The onBackgroundFetchTimeout method is called when the operating system is not executing a background task or the task cannot run within a given time. In this approach, we can process tasks with task ids.

void _onBackgroundFetch(String taskId) async {
if(taskId == ‘your_task_id’) {
print(' [BackgroundFetch] Event received ");//TODO:Perform your task like: Call the API's, call the DB and local notification.}}Copy the code

When the background service executes an event, the onBackgroundFetch method is called. In this method, we receive the task ID as a parameter that can be used to process the task. This is important in situations where you need to call an API to save data to a database or display local notifications, for example.

By default, the frequency of the interval after the task is 15 minutes. If you want to set it to something else, you can do it here as well. On Android, the minimum interval for background processes is 15 minutes. If the value is less than 15, Android uses 15 minutes by default.

Also, we must also remember to make changes inside the info.plist and manifest.xml file for both iOS & Android. We need to set some of the permissions, and we also need to copy and paste other settings. If you need these settings, you can get them at the following links: Android , OS.

In addition, we must remember to make changes to the Info.plist and manifest.xml files for Android IOS. We need to set some permissions, and we need to copy and paste other Settings. If you need these Settings, you can get them from the following links: IOS, Android.

Thanks for reading!


The elder brother of the © cat

  • WeChat ducafecat

  • Blog ducafecat. Tech

  • github

  • bilibili