Flutter Application crashing after WorkManager is called

467 views Asked by At

When I initialize the work manager in my Flutter Application it crashes.

ERROR BEING SHOWN

WorkManager Code

Workmanager().initialize(
                        callbackDispatcher, 
                        isInDebugMode: true 
                      );

                     Workmanager().registerPeriodicTask(
                        "2", 
                        "simplePeriodicTask", 
                        frequency: Duration(minutes: 15),
                      );

                      //callbackDispatcher
                       void callbackDispatcher() {
                        Workmanager().executeTask((task, inputData) {
                          log("Native called background task"); //simpleTask will be emitted here.
                          return Future.value(true);
                        });
                      }

       
2

There are 2 answers

0
Punnoose K Thomas On

I understand there might be many reasons for it including Kotlin version compatibility and Flutter version compatibility among many, but this is what worked for me.

At another area of the app, I invoked

await Workmanager().cancelByUniqueName('uniqueName');

For some reason, just removing that line from the app fixed the issue. I tried relocating it as an action button to a different page or even a call from the onDispose override function, but for some reason, as long as this line exists somewhere in the code, it keeps crashing.

So i just removed it completely and I used server API calls to make sure that new periodic instances aren't being created on initializing the WorkManager on each app open.

Hope this helps.

0
Muhtar On

You need to await workmanager initializing. It should be ;

    void main() async {
  WidgetsFlutterBinding.ensureInitialized();
     await Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
    await Workmanager().registerPeriodicTask("5",
     simplePeriodicTask,
        existingWorkPolicy: ExistingWorkPolicy.replace,
        frequency: Duration(minutes: 15), //when should it check the link
        initialDelay:
            Duration(seconds: 10), //duration before showing the notification
        constraints: Constraints(
          networkType: NetworkType.connected,
        ));
  }

void callbackDispatcher() {
    Workmanager().executeTask((task, inputData) async {
        log("Native called background task"); 
       return Future.value(true);
                        });