void main() async { // ... existing setup code ... const simpleTaskKey = "com.domain.myapp.taskId"; // Mandatory if the App is obfuscated or using Flutter 3.1+ @pragma('vm:entry-point') void callbackDispatcher() { Workmanager().executeTask((task, inputData) async { switch (task) { case simpleTaskKey: // Initialize PowerSync database and connection final currentConnector = await openDatabase(); db.connect(connector: currentConnector!); // Perform database operations await TodoList.create('New background task item'); await currentConnector.uploadData(db); await TodoList.create('testing1111'); await currentConnector.uploadData(db); // print("$simpleTaskKey was executed. inputData = $inputData"); break; } // Close database when done await db.close(); return Future.value(true); }); } // Initialize the workmanager with your callback Workmanager().initialize( callbackDispatcher, // Shows notifications during task execution (useful for debugging) isInDebugMode: true ); // ... rest of your app initialization ...}
Note specifically in the switch statement:
Copy
// currentConnector is the connector to the remote DB// openDatabase sets the db variable to the PowerSync databasefinal currentConnector = await openDatabase();// connect PowerSync to the remote databasedb.connect(connector: currentConnector!);// a database write operationawait TodoList.create('Buy new shoes');// Sync with the remote databaseawait currentConnector.uploadData(db);
Since WorkManager executes in a new process, you need to set up the PowerSync local database and connect to the remote database using your connector.
Run a write (in the case of this demo app, we create a ‘todo list’)
Make sure to run currentConnector.uploadData(db); so that the local write is uploaded to the remote database.