Writing
Mobile English

Offline-First Flutter: Architecture That Survives a Dead Signal

How I structure Flutter apps so they keep working in lifts, basements, and Sulawesi back roads - Hive, queued writes, and honest sync.

  • Published
  • 1 min read
On this page3 sections
  1. The three rules I build by
  2. The outbox in practice
  3. What this costs

Most apps are demoed on office Wi-Fi and used on a motorbike in the rain. If your app only works online, it only works in the demo.

The three rules I build by

  1. Reads never block on network. The UI renders from a local store (Hive) first. Network fills the cache; it never gates the first frame.
  2. Writes are queued, not sent. Every mutation goes into an outbox with an idempotency key. A sync worker drains it when connectivity returns.
  3. Conflicts are decided, not discovered. Last-write-wins is a decision. Server-wins is a decision. “We never thought about it” is an incident.

The outbox in practice

dart
@immutable
class PendingOp {
  final String id;        // uuid, doubles as idempotency key
  final String endpoint;
  final Map<String, dynamic> payload;
  final DateTime queuedAt;

  const PendingOp({required this.id, required this.endpoint, required this.payload, required this.queuedAt});
}

Future<void> drain() async {
  for (final op in box.values.sortedBy((o) => o.queuedAt)) {
    final res = await dio.post(op.endpoint,
      data: op.payload,
      options: Options(
        headers: {'Idempotency-Key': op.id},
        validateStatus: (s) => s != null && s < 500, // let 409 through instead of throwing
      ));
    if (res.statusCode == 200 || res.statusCode == 409) {
      await box.delete(op.id); // 409 = server already has it. Done is done.
    }
  }
}

The 409 branch matters. Retries will happen; the server treating a duplicate as success is what makes retries safe.

What this costs

Offline-first is not free: you maintain a local schema, a sync worker, and a conflict policy. But the alternative is a support inbox full of “the app lost my data” - and that costs more.