Can't execute async method in Background with workmanager
879
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.
Comments
-
Santo Shakil over 1 year
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(); } } ....... ....... }
-
Muhammed Refaat over 3 yearsI 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?
-
nvoigt over 3 yearsNot really, sorry, I don't know your code. You should ask a new question about your specific code and problem.