Skip to main content

A text note saved on disk

The smallest app with storage: a Dart program that keeps one text in a local database. Each run reads the note back and adds a line, under the same author. Pick the tab of your storage adapter: the program is the same, and only the lines that open the database change.

A text note saved on disk

A Dart program that keeps one collaborative text in a local database, with the storage adapter you pick. Every run reads the note back and adds a line.

import 'dart:io';

import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_lf_sqlite/crdt_lf_sqlite.dart';

/// Adds a line to the note stored in `note.db`, and returns the whole note.
Future<String> addLine() async {
final backend = CRDTSqlite.open('note.db');

// Reads the stored note (or starts an empty one), then writes every edit.
final note = await backend.openDocument('note');
final text = CRDTFugueTextHandler(note.document, 'body');

text.insert(text.value.runes.length, 'Hello 🌍\n');
final value = text.value;

await note.persistence.dispose(); // writes what is still waiting
note.document.dispose();
await note.persistence.storage.close();
backend.close();

return value;
}

Future<void> main() async {
// One more line on every run.
stdout.writeln(await addLine());
}

Key points

  • openDocument reads the stored note before it returns, and keeps the same author (peer id) on every run.
  • Close in this order: the persistence (it writes what is still waiting), the document, the storage, the backend.
  • The database of the adapter may need its own setup on some platforms: see the package it builds on.