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

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

}
5
  • Can you explain what you mean by "don't work" and why you don't await your async method? Commented Jul 22, 2020 at 15:00
  • Don't work means it wasn't executed. Commented Jul 22, 2020 at 15:01
  • You start it and then instead of waiting for it, immediately tell your caller you are done. I would not expect it to be executed completely under such conditions. Commented Jul 22, 2020 at 15:02
  • So what's the solution? Commented Jul 22, 2020 at 15:04
  • @nvoigt any solution. I am also facing same issue Commented Jan 27, 2023 at 12:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Not really, sorry, I don't know your code. You should ask a new question about your specific code and problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.