flutterdartflutter-workmanager

Flutter app crashing when attempting to register one-off task


By "crash" I mean the UI becomes unresponsive. The app does not close and no errors are shown in the VSCode Debug Console.

In main() I'm initializnig my callbackDispatcher:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  runApp(MyApp());
}

My callbackDispatcher lives in another file and looks like this:

void callbackDispatcher(){
  print('callbackDispatcher called');
  Workmanager().executeTask((task, inputData) async {
    switch(task){
      case "process_barcode":
        await getBarcodeDetails(inputData?['barcode']);
    }
    return Future.value(true);
  });
}

I would provide the code for getBarcodeDetails but my print statement is never called, so I don't think this function is ever even called.

Then in my app's UI there is a button which triggers the WorkManager task:

ElevatedButton.icon(
  icon: const FaIcon(FontAwesomeIcons.barcode),
  onPressed: () async {
    TaskMonitor tm = TaskMonitor();
    bool isBcPending = await tm.isTaskPending('bc_lookup');
    if(!isBcPending){
      // Get the barcode from the scanner
      var result = await BarcodeScanner.scan();
      print('Barcode: ${result.rawContent}');

      // Save the barcode data to the DB
      await dataProvider.setBarcode(result.rawContent);
      print('Barcode set!');

      // Set an event listener to do stuff when the barcode scan has completed.
      dataProvider.waitForEvent('bc_lookup_completed');
      print("Start event listener");

      // Do the HTTP request to get the barcode details.
      Workmanager().registerOneOffTask(
        'process_barcode', 
        'process_barcode', 
        inputData: {'barcode': result.rawContent}
      );
      print('Running the task..');
    }
  }, 
  label: const Text('Scan Barcode')
)

What's weird is that my last print statement in the onPress is called before the app freezes up, so I'm not sure where it's freezing up exactly, however, commenting out the call to Workmanager().registerOneOffTask() prevents the app from ever freezing.

The other weird thing is that there is no error messages or anything helpful at all in the debug console.

How can I determine the source of the problem?

(BTW, running on iOS currently, have not tried in Android yet)


Solution

  • There are a couple of issues.

    WorkmanagerPlugin.setPluginRegistrantCallback { registry in  
        // The following code will be called upon WorkmanagerPlugin's registration.
        // Note : all of the app's plugins may not be required in this context ;
        // instead of using GeneratedPluginRegistrant.register(with: registry),
        // you may want to register only specific plugins.
        AppDelegate.registerPlugins(with: registry)
    }
    

    After making these changes project builds and runs.