An app that silently loses data the moment 4G drops in an elevator or a parking garage reads as amateur work, even when the rest of the codebase is solid. Offline-first is not a feature you bolt on at the end with a caching package: it is an architectural decision that shapes how you model data, how screens are written, and how network failures are treated as first-class states rather than edge cases. Here is how to set that architecture up properly, along with the tradeoffs it genuinely imposes.
The concrete problem
A common case: a field app for deliveries, maintenance visits, or mobile sales. Users need to create an order, edit it, or check off a step without any connectivity, and once the connection comes back everything must reconcile with the REST backend without duplicates or lost updates.
The classic mistake is building a "read-through" cache with shared_preferences or Hive to speed up rendering, then wrapping HTTP calls in try/catch blocks to "retry later." That works in a demo. It breaks the moment a user creates two orders offline, comes back online, and ends up with a duplicate order or an update silently overwritten by a stale version.
Why this happens: the underlying mechanism
Offline-first breaks an assumption baked into most mobile architectures: that local state is a simple projection of server state. Once offline writes are allowed, you have two sources of truth that temporarily diverge, and reconciling them needs an explicit protocol:
- Lost ordering: mutations queued during an outage are not guaranteed to fire in creation order once connectivity returns, especially if the app is killed and relaunched by the OS mid-queue.
- Duplicates: a
POST /ordersreplayed after a network timeout (the server may have already processed it, only the response was lost) creates a second resource if there is no idempotency key. - Write conflicts: a record edited locally may have changed server-side in the meantime (another device, a back-office edit). Without an explicit resolution strategy, the last write always wins by default, which is not always the correct business outcome.
Ignore these three points and you build a system that looks fine on office Wi-Fi and falls apart in the field, exactly where offline-first was supposed to add value.
Diagnose before fixing
Before picking a solution, make the problem observable: how many mutations are pending, for how long, and how many fail silently.
enum SyncStatus { pending, syncing, synced, failed }
class SyncLogger {
static void log(String mutationId, SyncStatus status, {String? error}) {
debugPrint('[sync] $mutationId -> $status ${error ?? ''}');
// In production: forward to Sentry/Crashlytics tagged with mutationId
}
}
Logging every state transition of a mutation with a stable ID turns a vague support ticket ("sync is broken") into a traceable incident instead of a guessing game.
An architecture that actually holds up
The core idea: separate a local source of truth (SQLite via drift, or Isar), a REST client, and a sync service that orchestrates both. Screens never talk to the network directly; they read and write the local database, which becomes the only state the UI observes.
The local database as source of truth
// drift schema
class Orders extends Table {
TextColumn get id => text()(); // client-generated UUID
TextColumn get remoteId => text().nullable()();
TextColumn get payload => text()(); // order JSON
IntColumn get status => intEnum<SyncStatus>()();
DateTimeColumn get updatedAt => dateTime()();
DateTimeColumn get lastSyncedAt => dateTime().nullable()();
@override
Set<Column> get primaryKey => {id};
}
The local ID is a UUID generated at creation time, not the server ID. That is what lets you create an order offline, render it immediately, and link it to a remoteId once synced, without ever blocking the UI on a network response.
A mutation queue with idempotency
Every write goes through a persisted queue, not an in-memory retry that disappears if the app is killed.
class SyncQueue {
final AppDatabase db;
SyncQueue(this.db);
Future<void> enqueueCreateOrder(Order order) async {
await db.into(db.orders).insert(
OrdersCompanion.insert(
id: order.id, // client UUID, doubles as the idempotency key
payload: jsonEncode(order.toJson()),
status: SyncStatus.pending,
updatedAt: DateTime.now(),
),
);
}
Future<void> processPending(ApiClient api) async {
final pending = await (db.select(db.orders)
..where((o) => o.status.equalsValue(SyncStatus.pending)))
.get();
for (final order in pending) {
try {
final response = await api.post(
'/orders',
headers: {'Idempotency-Key': order.id},
body: order.payload,
);
await db.update(db.orders).replace(
order.copyWith(
status: SyncStatus.synced,
remoteId: Value(response['id']),
lastSyncedAt: Value(DateTime.now()),
),
);
} on DioException catch (e) {
if (e.response?.statusCode == 409) {
// Server-detected conflict: must be resolved, not dropped
await _handleConflict(order, e.response!.data);
}
// Otherwise: stays pending, retried on the next cycle
}
}
}
}
The Idempotency-Key header (the pattern Stripe popularized, now common on many internal APIs) needs backend support: if the key was already processed, the server returns the existing resource instead of creating a new one. This is the only reliable way to avoid duplicates on a replayed POST.
Detecting reconnection without busy-looping
final connectivitySubscription = Connectivity()
.onConnectivityChanged
.where((result) => result != ConnectivityResult.none)
.listen((_) => syncQueue.processPending(apiClient));
connectivity_plus saves you from reinventing network state detection, but a changed ConnectivityResult does not guarantee actual Internet reachability (a captive Wi-Fi portal with no real access fires the same event). For critical sync, a lightweight ping to a backend health endpoint before calling processPending avoids wasted failure cycles.
The tradeoffs worth naming explicitly
- drift/Isar vs Hive: Hive is simpler for key-value caching, but it has no relational schema or query layer, which becomes limiting fast once entities relate to each other (orders, line items, customers).
driftadds upfront boilerplate but gives you typed SQL queries and versioned migrations. - Automatic vs manual conflict resolution: last-write-wins is trivial to implement but silently loses business data. For critical fields (quantities, amounts), surfacing the conflict to the user is often safer than resolving it automatically.
- All-in-one packages (
brick,flutter_data) speed up a greenfield project but impose their own modeling conventions; worth it on a new codebase, less so when a REST client is already in place.
When the "simple" fix is not enough
This pattern (local queue + idempotency + reconnect handling) covers the large majority of business apps with a single owner per resource. It stops being sufficient once you need near real-time collaborative editing (several devices modifying the same resource concurrently): that calls for convergent data structures (CRDTs) or a server-authoritative sync with field-level diffing, not just an idempotency key. Similarly, if sync must continue while the app is closed, WorkManager on Android and background task scheduling on iOS (BGTaskScheduler via background_fetch) become necessary, each with its own OS-imposed execution limits.
Takeaway
Offline-first gets solved by making a local database the single source of truth for the UI, backing it with a persisted and idempotent mutation queue, and choosing an explicit conflict strategy instead of an implicit one. Existing packages (drift, connectivity_plus) handle the plumbing; the real architectural decision is who resolves conflicts, and at what point in the flow.
