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.
- main.dart
- open_note.dart
- note_page.dart
- Install
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'),
),
);
}
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:crdt_socket_sync/replica.dart';
import 'package:crdt_socket_sync/web_socket_relay_client.dart';
import 'package:flutter/foundation.dart';
/// Opens the note on this device, and syncs it through the relay at [url].
///
/// Completes once the local copy is ready, even when the relay is down.
Future<CRDTReplica> openNote(String url) async {
final replica = await CRDTReplica.open(
// The relay room: every peer of the note opens the same id.
documentId: 'note',
storage: CRDTHive.open,
sync:
(document) => WebSocketRelayClient(
url: url,
document: document,
author: document.peerId,
),
// Without it, a storage that cannot be read makes `open` throw. With it,
// the note starts empty and in memory.
onStorageError: (error, stack) => debugPrint('Storage error: $error'),
);
CRDTFugueTextHandler(replica.document, 'note');
return replica;
}
import 'dart:async';
import 'package:crdt_lf_flutter/crdt_lf_flutter.dart';
import 'package:crdt_socket_sync/client.dart';
import 'package:crdt_socket_sync/replica.dart';
import 'package:flutter/material.dart';
import 'open_note.dart';
/// A page that edits the note, stored on this device and synced through the
/// relay at [url].
class NotePage extends StatefulWidget {
/// Creates the page of the note synced through the relay at [url].
const NotePage({required this.url, super.key});
/// The address of the relay server.
final String url;
State<NotePage> createState() => _NotePageState();
}
class _NotePageState extends State<NotePage> {
late final Future<CRDTReplica> _replica = openNote(widget.url);
void dispose() {
// Stops the sync, writes what is still waiting, closes the storage.
unawaited(_replica.then((replica) => replica.close()));
super.dispose();
}
Widget build(BuildContext context) {
return FutureBuilder<CRDTReplica>(
future: _replica,
builder: (context, snapshot) {
final replica = snapshot.data;
if (replica == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Note'),
actions: [ConnectionChip(client: replica.client!)],
),
body: CrdtProvider.value(
value: replica.document,
child: CrdtTextFieldBuilder(
id: 'note',
builder:
(context, controller) => TextField(
controller: controller,
maxLines: null,
decoration: const InputDecoration(
hintText: 'Write here, online or not',
contentPadding: EdgeInsets.all(16),
),
),
),
),
);
},
);
}
}
/// Shows the connection status of [client].
class ConnectionChip extends StatelessWidget {
/// Creates a chip that follows the connection of [client].
const ConnectionChip({required this.client, super.key});
/// The client to follow.
final CRDTSocketClient client;
Widget build(BuildContext context) {
return StreamBuilder<ConnectionStatus>(
stream: client.connectionStatus,
// The stream replays nothing: start from the current status.
initialData: client.connectionStatusValue,
builder: (context, snapshot) {
final (label, icon) = switch (snapshot.requireData) {
ConnectionStatus.connected => ('Online', Icons.cloud_done),
ConnectionStatus.connecting => ('Connecting', Icons.cloud_upload),
ConnectionStatus.reconnecting => ('Reconnecting', Icons.cloud_sync),
ConnectionStatus.disconnected => ('Offline', Icons.cloud_off),
ConnectionStatus.error => ('Offline', Icons.cloud_off),
ConnectionStatus.unsupported => ('Update the app', Icons.error),
};
return Chip(avatar: Icon(icon, size: 18), label: Text(label));
},
);
}
}
flutter pub add crdt_lf crdt_lf_flutter crdt_lf_hive crdt_socket_sync hive \
path_provider
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.openrestores 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
onStorageErrorthe 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.