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.
- main.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();
// 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)));
}
import 'dart:async';
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_lf_flutter/crdt_lf_flutter.dart';
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:flutter/material.dart';
/// A page that edits the note stored in [backend].
class NotePage extends StatefulWidget {
/// Creates the page of the note stored in [backend].
const NotePage({required this.backend, super.key});
/// Where the note is stored.
final CRDTStorageBackend backend;
State<NotePage> createState() => _NotePageState();
}
class _NotePageState extends State<NotePage> {
PersistentDocument? _note;
void initState() {
super.initState();
unawaited(_open());
}
Future<void> _open() async {
// Reads the stored note (or starts an empty one), then writes every edit.
final note = await widget.backend.openDocument(
'note',
// Past this many stored changes, a snapshot replaces them.
compactAfter: 1000,
// Without it, a write that fails is silent.
onError: (error, stack) => debugPrint('Storage error: $error'),
);
CRDTFugueTextHandler(note.document, 'note');
if (!mounted) {
return _close(note);
}
setState(() => _note = note);
}
void dispose() {
final note = _note;
if (note != null) {
unawaited(_close(note));
}
super.dispose();
}
static Future<void> _close(PersistentDocument note) async {
await note.persistence.dispose(); // writes what is still waiting
note.document.dispose();
await note.persistence.storage.close();
}
Widget build(BuildContext context) {
final note = _note;
if (note == null) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
appBar: AppBar(title: const Text('Note')),
body: CrdtProvider.value(
value: note.document,
child: CrdtTextFieldBuilder(
id: 'note',
builder:
(context, controller) => TextField(
controller: controller,
maxLines: null,
decoration: const InputDecoration(
hintText: 'Write here',
contentPadding: EdgeInsets.all(16),
),
),
),
),
);
}
}
flutter pub add crdt_lf crdt_lf_flutter crdt_lf_hive hive path_provider
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
openDocumentreturns, under the id the widgets read. compactAfterkeeps the stored log short. A compaction drops the undo history of aCRDTUndoManager: leave it out where that matters, and callpersistence.compact()at a moment you choose.CrdtProvider.valuenever disposes the document: the page closes it indispose.