Open waynewcwu opened 2 years ago
Check if below workaround from https://github.com/flutter/flutter/issues/98473#issuecomment-1041895729 fixes the issue
Thanks for filing this; I've filed #98591 for the general problem (which we weren't aware of when updating the plugins).
While we investigate whether we can adjust Flutter to handle this automatically in the future, here's a workaround that should allow using the current versions of the plugins:
- Add dependencies on
shared_preferences_android
andshared_preferences_ios
.- At the beginning of your background isolate entry point, add something like:
if (Platform.isAndroid) SharedPreferencesAndroid.registerWith(); if (Platform.isIOS) SharedPreferencesIOS.registerWith();
@absar i didn't get the solution yet! please explain it
@mohammedsalem97 something like this.
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async{
if (Platform.isAndroid) SharedPreferencesAndroid.registerWith(); // here
if (Platform.isIOS) SharedPreferencesIOS.registerWith(); // and here
switch (task) {
case myTask:
int? totalExecutions;
final prefs = await SharedPreferences.getInstance(); //Initialize dependency
try { //add code execution
totalExecutions = await prefs.getInt("totalExecutions");
// prefs.setInt("totalExecutions",
// totalExecutions == null ? 1 : totalExecutions + 1);
}
catch (err) {
Logger().e(err.toString()); // Logger flutter package, prints error on the debug console
throw Exception(err);
}
break;
case Workmanager.iOSBackgroundTask:
print("iOS background fetch delegate ran");
break;
}
return Future.value(true);
});
}
The callback above runs in a different Isolate, while some plugins initialization is straight forward as when used in the main Isolate, some might require extra steps to work properly. You should use DartPluginRegistrant.ensureInitialized(); // Initialize dependency
When working with plugin in an isolate as well to be on a safer side.
Version
Describe the error I get the fail
I/WM-WorkerWrapper(25984): Worker result FAILURE for Work [ id=eaf19926-15cd-4ba9-8858-ab8ed99182aa, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
when I try to run the Debugging tips sample code in the README.md.Then I mark
final prefs = await SharedPreferences.getInstance();
andtry and catch
, it get worker result successful.May I ask same suggestion? Thanks.
My
main
full code as below:Output of
debug
Output of
flutter doctor -v