Set up offline sync
To set up offline sync, you add the offline sync packages, mark the tables to sync, open a local database on the device, and start the sync. Your app then reads and writes synced data on the device, and the sync keeps it up to date with the server.
Before you start
- Offline sync requires a signed-in user whose user id is a UUID, which Serverpod's authentication module provides by default.
Add the packages
Offline sync is a module with two packages, one for your server and one for your app. Add the server package to your server project, and the client package to your client project and your Flutter app. Also add serverpod_database to your client project, because the generated code for synced tables uses it. Run these commands from your project's root folder:
cd my_project_server
dart pub add serverpod_offline_sync_server
cd ../my_project_client
dart pub add serverpod_offline_sync_client
dart pub add serverpod_database
cd ../my_project_flutter
flutter pub add serverpod_offline_sync_client
The pub add command picks the newest version that works with your project's Serverpod version.
Mark the tables to sync
An existing table usually needs remodeling before it can sync. Marking it changes its id to a UUID and limits its relations to other synced tables. Model synced data lists the rules.
Offline sync only syncs the tables you mark. Mark each one, then regenerate the code and migrate the database:
-
Set
database: syncon each table model whose data should sync:class: Tasktable: taskdatabase: syncfields:title: Stringdone: bool, default=false -
Save the file. With
serverpod startrunning, Serverpod regenerates the code. If a model breaks one of the rules for synced tables that code generation checks, the terminal shows the error. -
In the
serverpod startterminal, press M to create and apply the migration. If you don't useserverpod start, follow Migrations instead.
The generated Task class differs from a normal table's class in two ways:
- UUID ids instead of numbers: Devices create rows while offline, so each row needs an id that no other device will make.
- An extra
spaceIdfield: It records who the row is shared with. Offline sync sets it, so don't set it yourself.
Your server needs no code of its own to sync. If your server code reads or writes synced tables, follow Read and write on the server.
Open the local database
In your Flutter app, after the user signs in, open the local database with createSyncSession, not createSession. Pass the user's id as persistentUserId:
import 'package:flutter/foundation.dart';
import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart';
final userId = client.auth.authInfo!.authUserId;
final session = await client.createSyncSession(
await resolveDatabasePath('tasks_$userId.db'),
isDebugMode: kDebugMode,
persistentUserId: userId,
);
The resolveDatabasePath helper comes from Create a session.
The session works like any client-side database session, including device migrations and the extra files web apps need. These points are specific to offline sync:
- Writes go to the user's personal space by default. Reads include every space the user belongs to. To write to a shared space, see Share data with spaces.
- One file per user keeps accounts apart. A file named after the user, like
tasks_$userId.db, gives each account on the device its own data. - The database opens offline. Only syncing needs the server.
- The session type is
OfflineSyncDatabaseSession. Use that type, notClientDatabaseSession, for fields and parameters that hold the session. - A watch updates when a sync brings in changes. To keep a widget up to date, watch a query.
Start the sync
Call syncOnce to sync once, for example on pull-to-refresh, or syncContinuously to keep syncing while the app runs:
// Sync once. Throws if the sync fails.
await client.offlineSync.syncOnce(session);
// Or keep syncing until you cancel.
final subscription = client.offlineSync.syncContinuously(session);
A continuous sync sends and receives changes as they happen, until you cancel it or the connection drops.
See sync working
Make a change on one device and watch it reach another:
- Sign in as the same user on two devices, such as two simulators.
- Start the sync on both devices.
- Add a task on one device. It appears on the other device after both have synced.
Restart after the connection drops
A continuous sync stops when the connection drops, and it doesn't restart by itself. To find out when it stops, await subscription.done. The await throws if the sync failed. Start a new sync when the device is back online, or after a short pause:
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart';
final updateRequired = ValueNotifier(false);
Object? _syncRun;
OfflineSyncSubscription? _subscription;
Completer<void>? _backOnline;
void _onConnectivityChanged(bool connected) {
final backOnline = _backOnline;
if (connected && backOnline != null && !backOnline.isCompleted) {
backOnline.complete();
}
}
Future<void> keepSyncing() async {
final run = Object();
_syncRun = run;
client.connectivityMonitor?.addListener(_onConnectivityChanged);
while (_syncRun == run) {
final backOnline = _backOnline = Completer<void>();
_subscription = client.offlineSync.syncContinuously(session);
try {
await _subscription!.done;
} on OfflineSyncTablesHashMismatchException {
// The app and the server have different synced schemas, so retrying
// won't help. Show an "Update required to sync" message.
updateRequired.value = true;
return;
} catch (_) {
// The connection dropped or the sync failed.
}
if (_syncRun != run) return;
// Try again when the device is back online, or after 5 seconds.
await Future.any([
backOnline.future,
Future<void>.delayed(const Duration(seconds: 5)),
]);
}
}
Future<void> stopSync() async {
_syncRun = null;
client.connectivityMonitor?.removeListener(_onConnectivityChanged);
await _subscription?.cancel();
}
Call keepSyncing after the user signs in. It listens to the FlutterConnectivityMonitor that a new Serverpod Flutter app attaches to the client. A new sync starts as soon as the device is back online, or after 5 seconds if the server is still unreachable. Each call owns its run, so a quick sign-out and sign-in never leaves two syncs running. Show an update prompt while updateRequired is true.
Close the database
When the user signs out, stop the sync before you close the session:
await stopSync();
await session.close();
Troubleshooting
- Sync fails with
ServerpodClientUnauthorized. The user isn't signed in, and sync only works for a signed-in user. Start the sync after the user signs in. - Sync fails with
OfflineSyncTablesHashMismatchException. The app and the server have different versions of the synced tables, because one of them is out of date. Update the one that's behind. See Change a synced schema. - Sync throws
This database is not an OfflineSyncDatabase. The session came fromcreateSession, which opens a local database without sync. Open the database withcreateSyncSessioninstead. - A server write throws
No user clock found for transaction or persistent user ID. Your server code wrote to a synced table outsidetransactionForUser. Run the write insidetransactionForUser, as Read and write on the server shows. - Sync fails with
OfflineSyncIntegrityViolationException. The server or the device rejected a change it couldn't merge, such as a row whose id another space already uses. It recorded the reason in itsoffline_sync_integrity_violationstable. When the server rejects the change, the device seesConnectionClosedExceptioninstead, and its sync keeps failing. Check that table on the server and on the device for the row (domainTableName,uuidRowId) and the reason (type), then fix that row.
Related
- Offline sync: how merges behave and the rules every write follows.
- Model synced data: the rules for synced tables, and patterns that keep edits from being lost, mixed, or duplicated.
- Share data with spaces: shared spaces, and how server code reads and writes synced tables.
- Test offline sync: offline sync in
withServerpodtests.