Flutter Offline-First: Sync Data That Survives Dead Zones
Build Flutter apps that keep working with no signal: local-first writes, a sync queue, conflict resolution, and server upserts — with production Dart code.
Gusti Randa
Flutter & Full-Stack Developer
Why Offline-First Is Not Optional
Most Flutter apps are built as if the network is always there. In production, it is not. Warehouse staff lose signal between shelves, delivery couriers pass through dead zones, and users in rural areas drop in and out of coverage all day. When your app assumes connectivity, every dead zone becomes a crash, a lost form, or a support ticket.
Offline-first flips the assumption: the local database is the source of truth, and the network is just a sync mechanism. The UI reads and writes locally, always fast, always available. Sync happens in the background whenever a connection appears.
This is how I build production Flutter apps that handle real-world connectivity, and it is simpler than most developers expect.
The Architecture in One Picture
Think of three layers:
- Local store — a real database on the device (Drift or Isar), not just SharedPreferences. This is what the UI reads from.
- Sync queue — a table of pending operations (create, update, delete) with a retry counter and a status.
- Sync engine — a service that drains the queue when online, resolves conflicts, and pulls down server changes.
The UI never talks to the API directly. It writes to the local store, the write enqueues a sync operation, and the engine handles the rest.
Step 1: Model Your Data for Sync
Every record that syncs needs three extra fields beyond its business data:
updatedAt— a timestamp for last-write-wins conflict resolutionisDirty— whether the record has unsynced local changesdeletedAt— soft delete, so a delete can sync instead of vanishing locally
class Order {
final String id;
final String customerName;
final double total;
final DateTime updatedAt;
final bool isDirty;
final DateTime? deletedAt;
const Order({
required this.id,
required this.customerName,
required this.total,
required this.updatedAt,
this.isDirty = false,
this.deletedAt,
});
}
Use UUIDs generated on the device as primary keys. Server-generated auto-increment IDs break offline creation, because you cannot create a record without a connection. Generate the ID locally, and the server accepts it as-is.
Step 2: Write Locally, Enqueue the Sync
Every mutation goes through one repository method. It writes to the local database and marks the record dirty in the same transaction, so the two can never drift apart.
Future<void> saveOrder(Order order) async {
final record = order.copyWith(
updatedAt: DateTime.now(),
isDirty: true,
);
await _db.ordersDao.upsert(record);
_syncEngine.kick(); // try to sync now, no-op if offline
}
The UI does not wait for the network. The save returns as soon as the local write completes, usually in a few milliseconds. The user sees their change immediately, online or not.
Step 3: The Sync Engine
The engine is a small loop with a simple job: push dirty records, then pull server changes since the last successful sync.
class SyncEngine {
Future<void> sync() async {
if (_isSyncing) return;
_isSyncing = true;
try {
await _pushPending();
await _pullChanges();
} finally {
_isSyncing = false;
}
}
Future<void> _pushPending() async {
final dirty = await _db.ordersDao.getDirty();
for (final order in dirty) {
try {
await _api.upsertOrder(order.toDto());
await _db.ordersDao.markClean(order.id);
} on ApiException catch (e) {
if (e.statusCode == 409) {
// Server has a newer version; keep local, resolve below.
await _resolveConflict(order);
} else {
// Leave dirty; next sync attempt will retry.
break;
}
}
}
}
}
A few rules that save you pain later:
- Push before pull. Local changes go up first, so a pull never overwrites something the user just did.
- Stop on the first network failure. If one request fails with a timeout, the rest will too. Break out and retry later instead of hammering a dead connection.
- Retry with backoff. A failed sync retries after 5 seconds, then 15, then 60. Never retry in a tight loop.
Step 4: Conflict Resolution
Conflicts are inevitable when two devices edit the same record. You need a policy before your first user hits one, not after.
Last-write-wins is the default for most apps. Compare updatedAt timestamps and keep the newer version. It is simple, predictable, and good enough for records where one person usually edits at a time, like orders or visit notes.
Future<void> _resolveConflict(Order local) async {
final server = await _api.getOrder(local.id);
if (server.updatedAt.isAfter(local.updatedAt)) {
await _db.ordersDao.upsert(server.toLocal(isDirty: false));
} else {
await _api.upsertOrder(local.toDto(), force: true);
await _db.ordersDao.markClean(local.id);
}
}
For records where losing an edit is unacceptable, like inventory counts, use field-level merge or server-wins with a local copy kept. The key point: decide the policy per entity, document it, and never silently drop a user's edit without a trace.
One practical detail: device clocks lie. A phone set five minutes fast will win every conflict. If your data matters, have the server stamp updatedAt on receipt and return it, so the server clock is the only clock that counts.
Step 5: Triggering Sync
Sync should happen without the user thinking about it:
- On app start and resume — the two moments a user most expects fresh data.
- On connectivity change — listen to
connectivity_plusand sync when the device comes back online. - After every local write — a cheap
kick()that no-ops when offline. - On a timer while the app is open — every 60 seconds is a reasonable default for field apps.
Connectivity().onConnectivityChanged.listen((results) {
if (results.any((r) => r != ConnectivityResult.none)) {
_syncEngine.sync();
}
});
Add a small sync indicator in the UI: a subtle "Synced" or "3 changes pending" label. Users trust an app that tells them the state of their data instead of hiding it.
What About the Server Side?
Offline-first needs a little server cooperation:
- Upsert endpoints instead of create-only POSTs, so a retried request does not create duplicates. Make them idempotent with a client-generated
requestIdor the record UUID itself. - A
sinceparameter on list endpoints, so the client pulls only what changed instead of the whole table. - Soft deletes on the server too, so a delete on one device propagates as a delete, not as a record that mysteriously reappears.
If you are building the backend in NestJS, this maps cleanly: an upsert endpoint with onConflict in your ORM, a updatedAt > :since query, and a deletedAt column. Nothing exotic.
Common Mistakes
- Treating the API response as the UI state. If the UI reads from the network, it breaks offline. Read from local, always.
- Syncing everything at once. Pull deltas, not full tables. A courier with 10,000 orders should not download all of them on every sync.
- No retry limit. A record that fails validation server-side will fail forever. After three attempts, mark it as errored and surface it to the user instead of retrying silently for weeks.
- Forgetting the delete path. Deletes are the most commonly broken sync operation. Soft delete everywhere, or accept ghost records.
The Payoff
Offline-first costs more upfront: a local database, a sync queue, and conflict handling are real work. But the payoff shows up fast in production. Forms never lose data, the app feels instant because reads are local, and support tickets about "the app crashed when I had no signal" disappear.
Start small. Pick one entity, usually the one users create in the field, and make it offline-first end to end. Once the pattern works for one table, repeating it for the rest is mostly copy and paste. Your users will not notice the architecture. They will notice that the app just works, everywhere.
Keep reading
Next.js Server Actions vs Route Handlers: When to Use Each
Server Actions and Route Handlers both run code on the server in Next.js, but they solve different problems. A practical guide to picking the right one, with real production code.
NestJS Validation Done Right: DTOs, Pipes, and Global Errors
Stop bad input from reaching your NestJS services. A practical guide to DTOs, class-validator, global ValidationPipe, and error responses your frontend can actually use.