Skip to main content

A text note in Flutter, saved on the device

A screen with one text field. The note is on the device from the first frame after it loads, and every keystroke is written down. Hive also runs in the browser, so the same code works on the web.

A text note in Flutter, saved on the deviceSource ↗

A Flutter app with one collaborative text field. Hive keeps the note on the device, also on the web, and every restart shows it again.

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();
// One backend for the whole app: it lives as long as the app does.
final backend = await CRDTHive.open();

runApp(MaterialApp(title: 'Note', home: NotePage(backend: backend)));
}

Key points

  • Set up the database of the adapter before you open the backend, as the documentation of the package it builds on explains.
  • Open one backend for the whole app, and pass it to the pages.
  • Create the handler on the document that openDocument returns, under the id the widgets read.
  • compactAfter keeps the stored log short. A compaction drops the undo history of a CRDTUndoManager: leave it out where that matters, and call persistence.compact() at a moment you choose.
  • CrdtProvider.value never disposes the document: the page closes it in dispose.