A list of notes: many documents in one app
An app with many notes keeps one document per note, and one storage backend for all of them. The list reads each note without following it; the note page opens one to edit it.
A list of notes: many documents in one appSource ↗
A Flutter app with a list of notes, one document each, kept on the device by Hive. The list reads each title without following the note, a tap opens the note to edit it, and a swipe deletes it.
- main.dart
- notes_page.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 'notes_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 holds every note.
final backend = await CRDTHive.open();
runApp(MaterialApp(title: 'Notes', home: NotesPage(backend: backend)));
}
import 'dart:async';
import 'package:crdt_lf/crdt_lf.dart';
import 'package:crdt_lf_hive/crdt_lf_hive.dart';
import 'package:flutter/material.dart';
import 'note_page.dart';
/// A note in the list: its document id and its title.
typedef NoteSummary = ({String id, String title});
/// The notes stored in [backend], without the ones in [except].
Future<List<NoteSummary>> readNotes(
CRDTStorageBackend backend, {
Set<String> except = const {},
}) async {
final notes = <NoteSummary>[];
for (final id in await backend.documentIds) {
if (except.contains(id)) {
continue;
}
// A read-only copy: nothing writes it, so dispose it after reading.
final document = await backend.readDocument(id);
final body = CRDTFugueTextHandler(document, 'body').value;
document.dispose();
final title = body.split('\n').first.trim();
notes.add((id: id, title: title.isEmpty ? 'Empty note' : title));
}
return notes..sort((a, b) => a.id.compareTo(b.id));
}
/// A page that lists the notes stored in [backend].
class NotesPage extends StatefulWidget {
/// Creates the list of the notes stored in [backend].
const NotesPage({required this.backend, super.key});
/// Where the notes are stored, one document per note.
final CRDTStorageBackend backend;
State<NotesPage> createState() => _NotesPageState();
}
class _NotesPageState extends State<NotesPage> {
List<NoteSummary>? _notes;
// A delete waits for these: a note still closing, and the reads running.
final _closing = <String, Future<void>>{};
final _loads = <Future<void>>{};
// The notes swiped away: the list skips them, even before the delete ends.
final _deleted = <String>{};
void initState() {
super.initState();
unawaited(_load());
}
Future<void> _load() async {
final load = _readNotes();
_loads.add(load);
try {
await load;
} finally {
_loads.remove(load);
}
}
Future<void> _readNotes() async {
final notes = await readNotes(widget.backend, except: _deleted);
if (mounted) {
// A read that started before a swipe still holds the deleted note.
setState(
() => _notes = [...notes.where((n) => !_deleted.contains(n.id))],
);
}
}
Future<void> _create() {
// The document id is the note id: any string that is unique in the app.
return _edit('note-${DateTime.now().microsecondsSinceEpoch}');
}
Future<void> _edit(String id) {
final closed = Completer<void>();
_closing[id] = closed.future;
return Navigator.of(context).push(
MaterialPageRoute<void>(
builder:
(context) => NotePage(
backend: widget.backend,
id: id,
// The list reloads once the note is written and closed.
onClosed: () {
closed.complete();
unawaited(_load());
},
),
),
);
}
Future<void> _delete(String id) async {
_deleted.add(id);
// A dismissed row must leave the list at once.
setState(() => _notes = [...?_notes?.where((note) => note.id != id)]);
// A note just left still writes its last edits: wait until it is closed.
await _closing.remove(id);
await Future.wait([..._loads]);
// The changes, the snapshots and the identity of the note.
await widget.backend.deleteDocument(id);
}
Widget build(BuildContext context) {
final notes = _notes;
return Scaffold(
appBar: AppBar(title: const Text('Notes')),
floatingActionButton: FloatingActionButton(
tooltip: 'New note',
onPressed: () => unawaited(_create()),
child: const Icon(Icons.add),
),
body:
notes == null
? const Center(child: CircularProgressIndicator())
: ListView(
children: [
for (final note in notes)
Dismissible(
key: ValueKey(note.id),
onDismissed: (_) => unawaited(_delete(note.id)),
child: ListTile(
title: Text(note.title),
onTap: () => unawaited(_edit(note.id)),
),
),
],
),
);
}
}
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 [id] stored in [backend].
class NotePage extends StatefulWidget {
/// Creates the page of the note [id] stored in [backend].
const NotePage({
required this.backend,
required this.id,
this.onClosed,
super.key,
});
/// Where the note is stored.
final CRDTStorageBackend backend;
/// The id of the note's document.
final String id;
/// Called once the note is written and closed, after the page is gone.
final VoidCallback? onClosed;
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(widget.id);
CRDTFugueTextHandler(note.document, 'body');
if (!mounted) {
return _close(note, widget.onClosed);
}
setState(() => _note = note);
}
void dispose() {
final note = _note;
if (note != null) {
unawaited(_close(note, widget.onClosed));
}
super.dispose();
}
static Future<void> _close(
PersistentDocument note,
VoidCallback? onClosed,
) async {
await note.persistence.dispose(); // writes what is still waiting
note.document.dispose();
await note.persistence.storage.close();
onClosed?.call();
}
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: 'body',
builder:
(context, controller) => TextField(
controller: controller,
maxLines: null,
autofocus: true,
decoration: const InputDecoration(
hintText: 'The first line is the title',
contentPadding: EdgeInsets.all(16),
),
),
),
),
);
}
}
flutter pub add crdt_lf crdt_lf_flutter crdt_lf_hive hive path_provider
Key points
- Open one backend for the whole app: it holds every note, and
documentIdslists them. - One document per note: the document id is the note id.
readDocumentbuilds a read-only copy for the list, and you dispose it after reading.openDocumentis for the page that edits the note.deleteDocumentremoves the changes, the snapshots and the identity of a note. A note just left may still be writing: wait until it is closed, then delete it.