5

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();
    }
  }

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

}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Santo Shakil
  • 981
  • 2
  • 13
  • 27

1 Answers1

4

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • I have used this same technique but the callback is not waiting for the await method and instead it just pass it to end the method execution, any idea about that? – Muhammed Refaat Jul 27 '20 at 11:54
  • Not really, sorry, I don't know your code. You should ask a new question about your specific code and problem. – nvoigt Jul 27 '20 at 15:30