April 13, 2021

Schedule background task in Flutter

By Mohit Agrawal

Let’s ask Flutter to do something for us in the background

scheduling_background_task_flutter1

Introduction

Hello devs ๐Ÿค , welcome back to another Flutter tutorial. In today’s tutorial, I will demonstrate to you how to schedule a background task in your Flutter app. First, Let’s clear that what is a background task and its need.

What is the background task in mobile applications?

In simple, the task which runs in the background even after closing the app is known as the background task. And we need it to perform some heavy time taking process. Let’s understand this with a simple example.

Suppose, you are making a download manager app using that user can download any files and save them on the device. Now if the user has to download some big file like 5GB then he can’t just keep open the app and for it to complete.

So, in this, you need to implement the background task in your app which will run the download process in the background. After completing the download you can notify the user.

More about Flutter Workmanager

We are going to use the Flutter Workmanager package to schedule a task in the Flutter application. WorkManager is a wrapper around Android’s WorkManager and iOS’ performFetchWithCompletionHandler, effectively enabling headless execution of Dart code in the background.

It is mainly useful when you want to schedule a periodic task

Implement background task using Flutter Workmanager package?

Let’s create a new Flutter app. I am using the android studio, you can use the visual studio as well. It’s your choice ๐Ÿ™….

Open pubspec.yaml and add the workmanager dependency like this.

workmanager: ^0.2.0

Now update the dependency.

flutter pub get

Now open your main.dart and copy paste the below code.

import 'package:workmanager/workmanager.dart';

const myTask = "syncWithTheBackEnd";

void callbackDispatcher() {
// this method will be called every hour
  Workmanager.executeTask((task, inputdata) async {
    switch (task) {
      case myTask:
        print("this method was called from native!");
        Fluttertoast.showToast(msg: "this method was called from native!");
        break;

      case Workmanager.iOSBackgroundTask:
        print("iOS background fetch delegate ran");
        break;
    }

    //Return true when the task executed successfully or not
    return Future.value(true);
  });
}

void main() {

  // needs to be initialized before using workmanager package
  WidgetsFlutterBinding.ensureInitialized();

  // initialize Workmanager with the function which you want to invoke after any periodic time
  Workmanager.initialize(callbackDispatcher); 

  // Periodic task registration
  Workmanager.registerPeriodicTask(
      "2",
      // use the same task name used in callbackDispatcher function for identifying the task
      // Each task must have a unique name if you want to add multiple tasks;
      myTask,
      // When no frequency is provided the default 15 minutes is set.
      // Minimum frequency is 15 min. 
      // Android will automatically change your frequency to 15 min if you have configured a lower frequency than 15 minutes.
      frequency: Duration(hours: 1), // change duration according to your needs
  );

  runApp(MyApp()); // at last lines, you can call runApp()
}

As you can see in the above code I have introduced a new method callbackDispatcher() and also modified the main() function.

Before initialising the MyApp(), we need to initialise the the work manager Workmanager.initialize(callbackDispatcher).

Now if you run this app and minimise it then you can see the toast notification in every 1 hour. It is because we have set the frequency of 1 hour in the above code. You can change it as per your requirement.

Video Tutorial

Conclusion

Thatโ€™s all guys, if you have any issues then please ask your doubts in the comment section.

Help me to grow our YouTube Channel: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below ๐Ÿ‘.
Thanks for reading!!!