ObjectBox for Flutter: Fast On-Device NoSQL in Practice
Hands-on guide to ObjectBox in Flutter: entity model, build_runner codegen, Store and Box CRUD, typed queries, ToOne/ToMany relations, and an honest comparison with Hive, Isar and Drift.
Published on • October 17, 2026
AI Assistant

Most Flutter apps eventually need more than SharedPreferences: a list of tasks that survives restarts, an offline cache of API results, or a local queue that syncs later. The usual reaction is to reach for the first package in the search results and discover three months later that reads are slow on large lists, or that you are hand-rolling JSON for what should have been a typed query.
ObjectBox takes a different route from the key-value stores: you annotate plain Dart classes, run a generator, and get a native ACID store with typed queries and built-in relations. This post walks the full path on a real project - dependencies, entity model, codegen, store setup, CRUD, queries, relations - and finishes with a comparison table against Hive, Isar and Drift so you can decide whether it fits your case.
What ObjectBox actually is
The pub.dev package page describes objectbox as a “Flutter database for super-fast NoSQL ACID compliant object persistence”, with the current stable release at 5.3.2 and a 6.0.0 preview line alongside it. It is a Dart API over a native C/C++ storage engine, which is why the package list on pub.dev shows Android, iOS, Linux, macOS and Windows as supported platforms - there is no web target in that list, so a Flutter web build needs a different solution (Hive, Drift over SQLite WASM, or IndexedDB-backed storage).
Three properties drive the design:
- Objects, not rows. You query with generated property objects (
User_.name), and results come back as instances of your entity class. There is no mapping layer to write or maintain. - Native core. Serialization uses FlatBuffers (a dependency of the package), so reading an object avoids the parse step you pay for with JSON-based stores.
- No SQL. Filters, ordering, aggregation and relation traversal are expressed through a Dart query builder rather than strings. If you need ad-hoc analytical SQL, this is not that tool.
Adding the packages
ObjectBox ships the runtime and the generator as separate packages. The documented setup for Flutter projects is:
$ flutter pub add objectbox objectbox_flutter_libs:any
$ flutter pub add --dev build_runner objectbox_generator:any
That produces the expected pubspec.yaml entries:
dependencies:
objectbox: ^5.3.2
objectbox_flutter_libs: any
dev_dependencies:
build_runner: ^2.4.11
objectbox_generator: any
Two platform notes from the official docs are worth doing now rather than debugging later: iOS apps must target iOS 15.0 (Podfile platform, IPHONEOS_DEPLOYMENT_TARGET, MinimumOSVersion) and macOS apps must target macOS 11.0.
If you want to run unit tests on your machine, the native database library has to exist on the host. The docs give a one-liner to run from a bash shell (Git Bash on Windows) in the package directory:
$ bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh)
The data model
An entity is a Dart class with exactly one 64-bit integer ID property and a no-argument constructor. That is the whole contract:
import 'package:objectbox/objectbox.dart';
@Entity()
class Task {
@Id()
int id = 0;
String title;
bool done;
DateTime due;
@Index()
String? label;
Task({this.title = '', this.done = false, DateTime? due, this.label})
: due = due ?? DateTime.now();
}
Details that bite people in practice:
- The ID must be non-private and of type
int.0means “not persisted yet”; ObjectBox assigns the next unused ID onput, and0xFFFFFFFFFFFFFFFFis reserved for internal use. @Index()is how you make equality, range and ordering conditions fast. Add it to the fields you filter or sort on, not to everything.- Adding or removing properties updates the model automatically after regeneration - no hand-written migration code. Renaming entities/properties or changing a type is a documented special case handled through the model file.
- Almost any type can be stored with a converter, including enums and custom value objects.
Generating code
$ dart run build_runner build
The generator scans lib (and test separately, so a test database can use its own entities) and writes two things:
| File | Purpose | Commit it? |
|---|---|---|
lib/objectbox.g.dart | Binding code, generated openStore(), entity metadata (Task_) | Yes |
lib/objectbox-model.json | Schema bookkeeping: stable IDs for entities and properties | Yes |
The model JSON is the important one. It keeps the unique IDs assigned to entities and properties, which is what allows an older install of your app to upgrade in place when you add a field. Commit it, and commit the diffs when the generator changes it. Re-run the generator whenever you touch an entity or upgrade the ObjectBox library.
Opening a store
openStore() is generated into objectbox.g.dart. The documented pattern keeps one Store alive for the whole app lifetime:
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'objectbox.g.dart';
class ObjectBox {
late final Store store;
late final Box<Task> tasks;
ObjectBox._create(this.store) {
tasks = store.box<Task>();
}
static Future<ObjectBox> create() async {
final docsDir = await getApplicationDocumentsDirectory();
final store = await openStore(directory: p.join(docsDir.path, 'tasks'));
return ObjectBox._create(store);
}
}
late ObjectBox objectBox;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
objectBox = await ObjectBox.create();
runApp(const MyApp());
}
If you omit directory, openStore() uses the app documents directory on mobile. On desktop, pass an explicit sub-directory so two apps do not collide. For tests, an in-memory database that writes no files is a directory of the form memory:test-db.
One isolate rule to remember: each Dart isolate has its own globals, but the native store is process-wide. In a background isolate, attach with Store.attach(...) instead of opening a second store.
CRUD
Everything hangs off Box<T>:
final box = objectBox.tasks;
// Create - returns the assigned ID, and mutates the object's id field
final id = box.put(Task(title: 'Write release notes'));
// Read
final task = box.get(id);
final all = box.getAll();
final some = box.getMany([1, 4, 9]);
// Update - same call, because put() upserts on ID
task?.done = true;
box.put(task!);
// Delete
box.remove(id);
box.removeMany([2, 3]);
box.removeAll();
// Count without materializing objects
final n = box.count();
put() runs an implicit transaction. When you write in a loop, batch instead: putMany() for lists, or an explicit transaction, because per-call puts each pay their own transaction cost.
Queries
A query is built in three steps: formulate conditions, build, then close when done. Conditions live on the generated Task_ class:
final builder = box
.query(Task_.done.equals(false)
& Task_.due.lessThan(DateTime.now().add(const Duration(days: 1))))
.order(Task_.due);
final query = builder.build();
try {
final overdue = query.find();
final count = query.count();
} finally {
query.close();
}
& and | are the Dart operator forms of and/or and add parentheses, so a & (b | c) reads the way you expect. Useful conditions beyond equals/lessThan: between, oneOf, startsWith, contains, isNull, and relationCount() on a to-many relation.
Practical query habits that matter:
-
Close queries.
close()frees native resources deterministically instead of whenever a finalizer runs. Atry/finallyaround a short-lived query is the cheapest insurance. -
Reuse a built query instead of rebuilding it for every keystroke. Parameters can be changed after
build(), and an alias lets two conditions on the same property be set independently:final q = box.query(Task_.label.equals('', alias: 'label')).build(); q.param(Task_.label, alias: 'label').value = 'work'; final results = q.find(); -
Paginate in the query, not in Dart:
query ..offset = 20 ..limit = 10; final page = query.find();In Dart these setters stick until you change them, unlike the Java API where they apply per
find()call. -
Case sensitivity defaults matter. String conditions are case-sensitive by default (
caseSensitive: falseopts out, orqueriesCaseSensitiveDefaulton the store), while ordering strings ignores case by default. -
Streams are a Dart feature:
query.stream()emits results as they change, which is the natural fit for aStreamBuilderUI. -
Aggregates run on a property query -
min,max,sum,avg,count,distinct- without building full objects. -
DateTime is stored as milliseconds internally; condition helpers such as
betweenDate()exist so you do not hand-convert toint.
Relations
Relations are modeled with ToOne<T> and ToMany<T> and are resolved lazily on first access, then cached:
@Entity()
class Customer {
@Id()
int id = 0;
String name;
@Backlink('customer')
final orders = ToMany<Order>();
}
@Entity()
class Order {
@Id()
int id = 0;
String text;
final customer = ToOne<Customer>();
}
Setting a relation is a plain assignment followed by a put of the owning object:
final order = Order(text: 'Order #1');
order.customer.target = customer; // or order.customer.targetId = existingId
store.box<Order>().put(order);
Under the hood a ToOne is stored as a target-ID property (named customerId by default, renameable with @TargetIdProperty). If the target has ID 0, ObjectBox puts it for you; if it already exists, only the relation is written. Editing a related object requires putting that object through its own box - store.box<Order>().put(orderToUpdate) - because putting the customer does not cascade property changes.
For to-many changes you can write only the relation delta instead of re-putting the whole entity:
customer.orders.removeAt(0);
store.box<Customer>().put(customer); // or customer.orders.applyToDb();
Querying across a relation uses linkMany() (and backlinkMany() for the reverse direction in Dart):
final b = box.query(Task_.label.equals('home'));
b.linkMany(Customer_.orders, Order_.text.contains('urgent'));
final hits = b.build().find();
Because relations load lazily, a list screen that touches customer.orders[0] for fifty rows performs fifty lookups. Keep them out of build methods, or batch the reads.
Async and isolates
Blocking the UI thread on a big write is the classic mistake. The Dart API has async variants of most box methods, plus transaction helpers that run in a worker isolate:
String? markDone(Store store, int taskId) {
final box = store.box<Task>();
final t = box.get(taskId);
if (t == null) return null;
t.done = true;
box.put(t);
return t.title;
}
await store.runInTransactionAsync(TxMode.write, markDone, taskId);
The callback must be a top-level function, static method, or a closure that captures only sendable values. For very high-volume inserts, putQueued() schedules a put and returns an ID immediately; store.awaitQueueSubmitted() / awaitQueueCompletion() let you flush before asserting or syncing.
Performance characteristics - honestly
ObjectBox is fast at what it is designed for: single-object reads by ID, indexed equality/range filters, and small-to-medium object graphs on mobile hardware. The pub.dev README claims “10x faster than SQLite” and ships a CRUD benchmark chart against sqflite and Hive - but the README itself notes that chart was last updated on 2021-09-11, and the reproducible benchmark app lives in the objectbox-dart-performance repository. Treat the headline number as directional marketing, not a measurement of your workload, and profile your own read path.
What you can rely on structurally:
- Reads by ID and indexed queries avoid scanning; that is the design center.
- Object construction is cheap enough that the docs call property queries (SQL-style projection) semi-deprecated - fetching full objects is usually not the bottleneck.
- There is a native library per platform, so cold start includes opening the store; do it once at app startup, not per screen.
- Cache invalidation is not your problem - there is no serialization cache to bust - but you do own query lifetime and relation access patterns.
When to pick it over Hive, Isar or Drift
All four persist data on the device; they differ in what you write and what you can ask.
| ObjectBox | Hive | Isar | Drift | |
|---|---|---|---|---|
| Data model | Annotated Dart classes | Boxes of JSON-able values / typed adapters | Annotated Dart classes | Tables defined in Dart, SQLite underneath |
| Query surface | Typed builder, indexes, relation links, streams | Key lookup + manual filtering in Dart | Typed builder with indexes and links | Full SQL, joins, migrations, streams |
| Codegen | build_runner (objectbox.g.dart) | TypeAdapters (or no codegen for basic boxes) | build_runner generator | build_runner (tables, DAOs) |
| Web support | Not in the supported platform list | Yes | Dart/FFI based; check your target | SQLite-based, works wherever SQLite does |
| Relations | ToOne / ToMany with @Backlink | Manual ID bookkeeping | @Link / @Backlink | Foreign keys and SQL joins |
| Sweet spot | Local-first apps with relational data and heavy queries | Simple key-value settings, small caches | Dart-native lists with filtering | Anything where you think in SQL |
Rules of thumb:
- Pick ObjectBox when your entities reference each other, you filter and sort often, and you want query results as objects without writing a repository layer.
- Pick Hive when the data really is a key-value map - feature flags, tokens, small settings - and you do not need to ask questions of it.
- Pick Isar if you like its query ergonomics and need web, or already use it.
- Pick Drift when the domain is genuinely relational across many tables, you rely on SQL features (window functions, complex joins, migrations you control), or you must run the same logic against SQLite on a server.
A useful migration property: the model JSON means adding fields to an ObjectBox entity does not require migration code, which keeps it pleasant for long-lived consumer apps where schema drift across installs is the real risk.
Checklist
-
objectbox,objectbox_flutter_libsand the devobjectbox_generatorare inpubspec.yaml, and iOS/macOS deployment targets are at least 15.0 / 11.0. - Every entity has exactly one non-private
intID with@Id(), a no-arg constructor, and@Index()on fields you filter or sort by. -
objectbox.g.dartandobjectbox-model.jsonare committed, and the generator runs in CI or a pre-commit hook after model changes. - One
Storeis opened at startup inmain(); background isolates useStore.attach, never a second store. - Every query is closed (
try/finally), hot queries are built once and reused, and pagination usesoffset/limitinstead of slicing lists in Dart. - Multi-step writes run inside
runInTransactionAsync(or a bulkputMany) rather than per-object puts on the UI isolate. - Related objects are updated through their own
Box, and lazy relation access stays out ofbuild()methods. - The choice of ObjectBox over Hive/Isar/Drift is a deliberate one: relational queries and local-first reads vs key-value simplicity vs SQL.
Sources: objectbox on pub.dev, ObjectBox documentation, ObjectBox getting started, ObjectBox queries, ObjectBox relations