Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background tasks with Workmanager plugin don't work in flutter

I'm trying to trigger some background tasks with a button and am finding the workmanager plugin for flutter to be very temperamental. It works occasionally but this is few and far between.

I'm testing it with this basic app:

import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';

const task1 = "simpleTask";

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager.initialize(
      callbackDispatcher, 
      isInDebugMode: true, 
  ); 
  //Workmanager.registerPeriodicTask("1", task1, initialDelay: Duration(seconds: 10), frequency: Duration(minutes: 15));
  //Workmanager.registerOneOffTask("1", task1, initialDelay: Duration(seconds: 5));
  runApp(MaterialApp(
  home: Scaffold(
    body: Container(
      color: Colors.blueAccent[400],
      child: Center(
        child: RaisedButton(
          child: Text("create notification in five seconds"),
          onPressed: () {
            Workmanager.registerOneOffTask("1", task1, initialDelay: Duration(seconds: 5));
          },
        ),
      ),
    ),
  ),
));}


void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    print("it's doing the task");
    switch (task) {
      case task1:
        print(task1);
        break;
      case Workmanager.iOSBackgroundTask:
        print("iOS background fetch delegate ran");
        break;
    }
    return Future.value(true);
});
}

I'm trying to trigger a background task from a button because it wasn't working as I had it before where the two lines are commented out. I have also never had the Workmanager.registerPeriodicTask work. This could be that the initial delay doesn't set off the first task at the end but instead starts the 15-minute timer until the first one but it's a massive pain to test given that I have to wait for a minimum of 15 minutes.

Is there a command that I'm missing or a necessary await that I'm missing or something?

Edit: I've just tested it on an Android emulator from AndroidStudio and the notifications all work exactly as they should for both one-off and periodic tasks so I think it is something to do with the phone maybe. Not really sure what to do about it though.

like image 794
Oliver Nicholls Avatar asked Sep 14 '25 16:09

Oliver Nicholls


1 Answers

I fixed this error by adding @pragma(‘vm:entry-point’) on a top line of headless (top-level) callbackDispatcher function. So like this:

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    print("Native called background task: $task");
    ....
    return Future.value(true);
  });
}

Source: https://learnpainless.com/flutter/flutter-workmanager-not-working-in-release-mode-working-in-debug-mode/

like image 163
Wanderson Santos Avatar answered Sep 17 '25 05:09

Wanderson Santos