Im trying to do a periodic background task that uploads some information, the information that i need is in local sqlite database but I cant acces it like i do out of the workmanager task, it gives me a message that de database is not initialized.
Here is the CallbackDispatcher
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) {
// Your background task logic goes here
debugPrint("TASK: {$task}");
debugPrint(DateTime.now().toString());
switch (task) {
case finishEvaluationTask:
ScheduledTask.control();
break;
case periodicEvaluationTask:
debugPrint("Hello from periodic Evaluation");
ScheduledTask.control();
break;
default:
debugPrint("Hello from switch case default");
}
// Inform back that background task run successfully
return Future.value(true);
});
}
Here is part of the function that i use and here is where my manager doesnt works, but it does work when I used it outside of Workmanager
class ScheduledTask {
static Future<void> control() async {
DtUserStruct user = FFAppState().user;
SQLiteManager manager = SQLiteManager.instance;
debugPrint("Before instance");
debugPrint(user.toString());
debugPrint(manager.toString());
debugPrint(user.name);
try {
//Check Batchs to update status
List<EvaluationSyncDetailsRow> finisheEvaluationList =
await manager.getAllFinishedEvaluationsSyncSended();
I have try declaring manager on main class and try to use it on the workmanager task but that doesnt work.
Here is part of my SQLiteManager class
class SQLiteManager {
SQLiteManager._();
static SQLiteManager? _instance;
static SQLiteManager get instance => _instance ??= SQLiteManager._();
static late Database _database;
Database get database => _database;
static Future initialize() async {
if (kIsWeb) {
return;
}
_database = await initializeDatabaseFromDbFile(
'dunometrics',
'dunometrics.db',
);
}
I have read something about Isolates, but I dont know how to use that to solve it.
Well i have try many things and none of them worked, and as answered in this question Flutter: Unable to execute database CRUD inside dart Isolate It seems that it is not possible.
If you are facing something similar, i solved what i wanted to do by using SharedPreferences with reload before get/set, and in that way you can send/recieve info between the main and the workmanager task, that was enough for me.
But if you really want to acces an sqlite database from workmanager task, then you can use Drift to create your database and then you will be able to acces the data between diferent isolates. Accessing drift databases on multiple isolates.
Hope this helps someone facing the same...