Skip to main content

An offline-first Flutter app: storage and sync in one call

CRDTReplica.open reads the note from the device, then connects. With no network the app still opens and keeps every edit, and sends them when the connection comes back.

An offline-first Flutter app: storage and sync in one callSource ↗

A Flutter note that opens from the device at once, then syncs through a relay server. CRDTReplica opens the storage and the client in the right order, and edits made offline reach the other devices later.

Flutter nativeFlutter web✓ tested in CI
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';

import 'note_page.dart';

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

// On the web Hive uses IndexedDB and needs no path.
if (!kIsWeb) {
Hive.init((await getApplicationDocumentsDirectory()).path);
}
CRDTHive.initialize();

runApp(
const MaterialApp(
title: 'Note',
// A relay server, such as WebSocketRelayServer of crdt_socket_sync.
home: NotePage(url: 'ws://localhost:8080'),
),
);
}

Key points

  • Every peer opens the same documentId.
  • A relay creates a room on demand. A server–client server knows only the documents you register on it.
  • CRDTReplica.open restores the local copy, then connects in the background: it completes with the server down, and the offline edits are sent on the next connection.
  • With onStorageError the app keeps going when the storage cannot be read: the note starts empty, in memory.
  • replica.close() stops the sync, writes what is still waiting, and closes the document and the storage.