Sub topic 11
Embedded NoSQL and object stores
This chapter assumes you have read the earlier chapters on shared_preferences, files and sqflite. It also assumes you are comfortable with Dart Futures and with the Note model and its toMap and fromMap methods. Here you learn what an embedded NoSQL store is, which options exist for Flutter, and when one fits better than SQLite.
What "embedded NoSQL" means
An embedded database runs inside your app process. It has no server and no network connection. SQLite is embedded too, so the "embedded" part is not what separates these stores from it. The difference is the data model.
SQLite stores rows in tables with a fixed schema, and you query it with SQL. NoSQL stores skip that. Here, NoSQL means "not a relational, SQL-based store". It covers several models:
- A key-value box. You store a value under a key and read it back by that key (Hive).
- A document store. You store nested map-like records and query by field (sembast).
- An object store. You store Dart objects directly and query through a typed API (ObjectBox, Isar).
These stores let you save objects without writing CREATE TABLE statements or SQL strings. The cost is that you give up joins, SQL, and the large body of tooling around relational databases.
The main options
| Package | Model | Implementation | Notes |
|---|---|---|---|
| Hive (`hive_ce`) | Key-value boxes | Pure Dart | Fast, simple, no query language. The original `hive` package is no longer actively maintained, and `hive_ce` is a community fork with the same API. |
| sembast | Document store | Pure Dart | Stores records in a single file. Supports filters and sorting. Has a web implementation. |
| ObjectBox | Object database | Native library plus generated Dart code | Typed queries, relations between objects, optional sync product. |
| Isar | Object database | Native library plus generated Dart code | Typed queries and indexes. The original package has had little maintenance, and community forks exist. |
Maintenance status changes. Before you choose a package, check its pub.dev page for the last release date, open issues and platform support. A storage package that is abandoned is a risk, because your users' data lives in its file format.
Hive: boxes of values
A Hive store is called a box. A box maps keys to values. The code below stores each Note as a plain map, which Hive can store without any extra setup. It uses the Note class from the earlier chapter.
import 'package:hive_ce_flutter/hive_ce_flutter.dart';
Future<Box<Map<dynamic, dynamic>>> openNotesBox() async {
await Hive.initFlutter();
return Hive.openBox<Map<dynamic, dynamic>>('notes');
}
Future<int> addNote(Box<Map<dynamic, dynamic>> box, Note note) {
return box.add(note.toMap()..remove('id'));
}
List<Note> allNotes(Box<Map<dynamic, dynamic>> box) {
return box.keys.map((key) {
final map = Map<String, Object?>.from(box.get(key)!);
map['id'] = key as int;
return Note.fromMap(map);
}).toList();
}
Future<void> deleteNoteById(Box<Map<dynamic, dynamic>> box, int id) {
return box.delete(id);
}Points to notice:
Hive.initFlutter()picks an app directory for you and must run once before you open a box.box.addgenerates an auto-incrementing integer key and returns it. We copy that key into theidfield when reading.- Maps come back typed as
Map<dynamic, dynamic>. You must convert them toMap<String, Object?>yourself, which is whatMap<String, Object?>.fromdoes. - Hive loads a box fully into memory when you open it. Reads such as
box.getare then synchronous and fast. A very large box therefore costs memory and start-up time. - There is no query language. To find notes by title, you iterate
box.valuesand filter in Dart. That is fine for hundreds of records and slow for hundreds of thousands.
Hive can also store your own classes if you write a type adapter, which is a class that tells Hive how to write and read the type. Adapters assign each field a numeric index, and you must never reuse or change those indexes for existing data. This is the Hive equivalent of a schema migration, and it is easy to get wrong.
sembast: documents with filters
sembast stores records in "stores", and each record is a map. Unlike Hive, it can filter and sort records without loading your own loop code. It is written in pure Dart, so it needs no native build setup. The whole database lives in one file, which you place with the path_provider knowledge from earlier chapters.
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast_io.dart';
final _store = intMapStoreFactory.store('notes');
Future<Database> openSembast() async {
final dir = await getApplicationDocumentsDirectory();
await dir.create(recursive: true);
return databaseFactoryIo.openDatabase(join(dir.path, 'notes_sembast.db'));
}
Future<int> insertNoteDoc(Database db, Note note) {
return _store.add(db, note.toMap()..remove('id'));
}
Future<List<Note>> searchNoteDocs(Database db, String title) async {
final snapshots = await _store.find(
db,
finder: Finder(filter: Filter.equals('title', title)),
);
return snapshots
.map((s) => Note.fromMap({...s.value, 'id': s.key}))
.toList();
}
Future<void> updateNoteTitle(Database db, int id, String title) async {
await _store.record(id).update(db, {'title': title});
}
Future<void> deleteNoteDoc(Database db, int id) async {
await _store.record(id).delete(db);
}Compare this with the sqflite version. There is no onCreate callback and no table definition. The Finder with Filter.equals plays the role of the where and whereArgs pair. Values are passed as data, never spliced into a query string, so injection is not a concern here either.
sembast keeps the file in an append-style format and rewrites it to compact it from time to time. Like Hive, it is best suited to modest data sizes.
Object stores: ObjectBox and Isar
ObjectBox and Isar work differently from the two stores above. You annotate a Dart class, run build_runner to generate code, and then read and write instances of that class through a generated API. A typical ObjectBox entity looks like a normal class with @Entity() above it and an @Id() field. You then call store.box<Note>().put(note) to save.
What you gain:
- Typed queries that the compiler checks, such as "notes where title equals X, ordered by date".
- Indexes on chosen fields for fast lookups.
- Relations between objects, for example a note that links to a folder.
- Good performance with large collections, because the engine is native code rather than Dart.
What you pay:
- A native library for each platform. This adds app size and can complicate builds, for example web support may be missing or limited.
- Generated code and a
build_runnerstep in your workflow. - A storage format owned by one package. If the package is abandoned, moving your data out means writing an export tool.
Schema changes without a schema
NoSQL stores do not force you to declare a schema, but your Dart classes still have one. Suppose version 2 of your app adds a pinned field to Note. Records saved by version 1 do not contain it. If fromMap reads map['pinned'] as bool, it throws on old records, because the value is null.
The fix is to read new fields defensively:
final pinned = (map['pinned'] as bool?) ?? false;This replaces the ALTER TABLE migration in SQLite with a default value in code. For changes that are more than adding a field, such as renaming a field or changing its type, write a one-time migration. Store a version number, for example in shared_preferences, and on start-up rewrite old records when the stored version is lower than the current one. Object stores such as ObjectBox handle simple additions for you but still need care for renames.
Choosing between SQLite and NoSQL
Use these rules of thumb:
- Pick SQLite when your data has relations, you need joins or aggregates, or you want a stable, well-known file format that other tools can open.
- Pick Hive or sembast when you store independent records, the data fits comfortably in memory, and you want minimal setup.
- Pick ObjectBox or Isar when you have many objects, need indexed queries, and accept generated code and a native dependency.
- Do not use any of these for secrets. Tokens and passwords still belong in secure storage.
Hide whichever store you choose behind a repository class, as covered in the repository chapter. If the store later proves a poor fit, only the repository changes, and your widgets stay the same.
Common mistakes
- Opening the same box or database more than once. Open it once, keep the reference, and reuse it.
- Forgetting
Hive.initFlutter()beforeopenBox, which fails because Hive has no storage path. - Treating
Map<dynamic, dynamic>asMap<String, Object?>without conversion, which throws a type error at run time. - Changing a Hive adapter's field indexes after release, which corrupts the reading of existing data.
- Putting very large lists, such as thousands of images as bytes, into a memory-loaded box.
Exercise
Your app saved notes with a version 1 model. Version 2 adds a boolean pinned field. You use sembast and do not run any migration. Write the line in fromMap that reads pinned so that old records still load, and say what value old records get.
Show answer
Use final pinned = (map['pinned'] as bool?) ?? false;. Records saved by version 1 have no pinned key, so map['pinned'] is null, the cast to bool? succeeds, and the ?? operator supplies false. Old notes load as not pinned.
Exercise
A fitness app stores 200,000 workout entries. Users filter them by date range and exercise name, and want totals per week. Should you pick Hive, SQLite, or neither? Give two reasons.
Show answer
SQLite (with sqflite or drift). First, Hive loads the whole box into memory and has no query language, so filtering 200,000 entries means scanning them all in Dart. Second, totals per week are an aggregate query, which SQL does with GROUP BY and an index on the date column. An object store such as ObjectBox would also be a reasonable choice, but SQLite handles aggregates directly.