Search code examples
flutterdartasync-awaitbackground-process

Can't execute async method in Background with workmanager


In my app, I need to execute some tasks in the background (while app is not running in foreground). I'm able to execute some methods in the background but, I need to execute an async method in the background which I can't.

Here is a part of my code:

void main() {
  runApp(MaterialApp(
    home: Home(),
  ));

  Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager.registerPeriodicTask("1", "simplePeriodicTask",
      existingWorkPolicy: ExistingWorkPolicy.replace,
      frequency: Duration(minutes: 15),
      initialDelay:
          Duration(seconds: 5),
      constraints: Constraints(
        networkType: NetworkType.connected,
      ));
}

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    _HomeState().manager();//This is not Working
    print('Background Services are Working!');//This is Working
    return Future.value(true);
  });
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  void initState() {
    login();
    super.initState();
  }

  void manager() async {
    if (account == null) {
      await login();
      await managerLocal();
      managerDrive();
    } else {
      await managerLocal();
      managerDrive();
    }
  }

  .......
  .......

}

Solution

  • You need to wait for your method to actually finish:

    void callbackDispatcher() {
      Workmanager.executeTask((task, inputData) async {
        await _HomeState().manager();
        print('Background Services are Working!');//This is Working
        return true;
      });
    }
    

    Your manager method should probably return a Future<void>, since it is async.

    If you are unsure how to work with Future data, feel free to have a look here.