← Back to posts Cover image for Mastering Offline-First Flutter: Building Robust Sync Engines for Intermittent Connectivity

Mastering Offline-First Flutter: Building Robust Sync Engines for Intermittent Connectivity

· 4 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

Offline-first sounds simple: write locally, sync later. The hard part is that “later” can mean after a crash, after an app update, after two devices edit the same record, or after your data schema has changed twice. A robust sync engine is not just a network call with retry logic — it is a system for safely replaying intent.

Persist writes before syncing

Treat every local mutation as a pending operation. The UI should respond to the local database immediately, while a separate outbox holds the change until the server confirms it.

class OutboxEntry {
  const OutboxEntry({
    required this.operationId,
    required this.entityType,
    required this.entityId,
    required this.payload,
    required this.schemaVersion,
  });

  final String operationId;
  final String entityType;
  final String entityId;
  final Map<String, dynamic> payload;
  final int schemaVersion;
}

Future<void> saveTask(Task task) async {
  await taskDao.save(task);

  await outboxDao.insert(
    OutboxEntry(
      operationId: uuid.v4(),
      entityType: 'task',
      entityId: task.id,
      payload: task.toJson(),
      schemaVersion: currentSchemaVersion,
    ),
  );
}

The key detail is that the queue must survive restarts. If the app is killed after the local write but before the sync, the operation still needs to be available on the next launch.

Make retries boring and safe

Network failures are normal, but duplicate writes are not. Every queued operation should carry a stable operationId. The server can then decide whether the request is new or has already been applied.

Future<void> flush() async {
  final pending = await outboxDao.pending();

  for (final entry in pending) {
    final result = await api.push(
      operationId: entry.operationId,
      entityType: entry.entityType,
      entityId: entry.entityId,
      schemaVersion: entry.schemaVersion,
      payload: entry.payload,
    );

    if (result.status == SyncStatus.applied ||
        result.status == SyncStatus.duplicate) {
      await outboxDao.markSent(entry.operationId);
    } else if (result.status == SyncStatus.conflict) {
      await resolveConflict(entry, result.remoteEntity);
      await outboxDao.markSent(entry.operationId);
    }
  }
}

This makes retries idempotent. If the app crashes mid-flush, the same operation can be sent again without creating a duplicate task, payment, message, or record.

Resolve conflicts with version vectors

Timestamps are tempting, but clocks drift, and “last write wins” can silently delete real work. For multi-device editing, version vectors are usually a better fit.

class VectorClock {
  VectorClock(this.counters);
  final Map<String, int> counters;

  VectorClock merge(VectorClock other) {
    final merged = Map<String, int>.from(counters);

    other.counters.forEach((replicaId, value) {
      final current = merged[replicaId] ?? 0;
      if (value > current) merged[replicaId] = value;
    });

    return VectorClock(merged);
  }

  bool isBefore(VectorClock other) {
    final replicas = {...counters.keys, ...other.counters.keys};
    var isBehind = false;

    for (final replica in replicas) {
      final mine = counters[replica] ?? 0;
      final theirs = other.counters[replica] ?? 0;

      if (mine > theirs) return false;
      if (mine < theirs) isBehind = true;
    }

    return isBehind;
  }
}

Future<void> resolveConflict(OutboxEntry local, Entity remote) async {
  final localClock = VectorClock(
    Map<String, int>.from(local.payload['clock'] ?? {}),
  );
  final remoteClock = remote.clock;

  if (remoteClock.isBefore(localClock)) return;

  if (localClock.isBefore(remoteClock)) {
    await entityDao.replace(remote);
    return;
  }

  final mergedClock = localClock.merge(remoteClock);
  final resolved = await resolver.pick(local.payload, remote.payload);

  await entityDao.save({
    ...resolved,
    'clock': mergedClock.counters,
  });
}

The important part is the three-way decision:

  • If the remote version is older, keep the local version.
  • If the local version is older, accept the remote version.
  • If neither is before the other, they are concurrent, so you need a merge strategy.

That strategy can be automatic field merging, manual user choice, or a domain-specific rule like “task status wins over due date changes.”

Migrate data before you sync it

Schema drift is where many sync engines quietly fail. If an older client sends a payload with created while the server expects createdAt, you need an explicit migration path.

typedef Migration = Map<String, dynamic> Function(Map<String, dynamic>);

final migrations = <int, Migration>{
  2: (data) {
    data['createdAt'] = data['created'];
    data.remove('created');
    return data;
  },
};

Map<String, dynamic> migrate(
  Map<String, dynamic> data,
  int from,
  int to,
) {
  for (var version = from + 1; version <= to; version++) {
    final migration = migrations[version];

    if (migration == null) {
      throw StateError('Missing migration to schema version $version');
    }

    data = migration(data);
  }

  return data;
}

Before sending a queued write, migrate it to the current schema. Before applying a remote change locally, migrate it to the local schema. Versioning the payload makes sync failures debuggable instead of mysterious.

Common mistakes to avoid

  • Replaying payloads without operation IDs.
  • Treating conflicts as an afterthought.
  • Relying only on wall-clock timestamps.
  • Letting schema changes break sync silently.
  • Keeping the outbox only in memory.

Offline-first Flutter apps work best when local state is the source of truth, queued writes are explicit, retries are idempotent, and conflicts are designed for. That is how you build a sync engine that survives real devices, real networks, and real user behavior.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.