Sub topic 17
Moving database work off the main isolate
This chapter assumes you can write a drift database with tables, a database class, and watch() queries, and that you know Dart isolates are separate memory heaps that communicate by message passing. You will learn when database work blocks the UI, how to run drift's SQLite connection on a background isolate, and how to share one database between isolates.
Why the main isolate matters
Flutter draws frames on the main isolate. At 60 frames per second, each frame has roughly 16 ms of budget. Anything that holds the main isolate longer than that causes dropped frames.
Dart's await does not move work to another thread. A plain drift NativeDatabase calls SQLite through dart:ffi, and those calls are synchronous. While SQLite runs a query, the isolate that called it is blocked. The Future returned by drift only hides this.
Most queries are fast, so you can ignore the issue for small tables. It becomes visible in these cases:
- Inserting or updating thousands of rows, even inside a transaction.
- Scans over large tables with no useful index.
watch()queries that re-run after every write to a busy table.- The first open of a database that runs a long migration.
Choosing where SQLite runs
| Setup | Where SQLite runs | Typical use |
|---|---|---|
| `NativeDatabase(file)` | Calling isolate | Tests, small tools, command-line code |
| `NativeDatabase.createInBackground(file)` | One drift-managed background isolate | Most apps |
| Shared connection across isolates | Background isolate with several clients | Apps that also do work in their own isolates |
The database class does not change between these setups. You only change the QueryExecutor you pass to it. That is why the AppDatabase([QueryExecutor? executor]) constructor from earlier chapters is worth keeping.
How a background connection works
With createInBackground, drift starts a new isolate and opens the SQLite file there. Your AppDatabase object stays on the main isolate. When you call select(...).get(), drift builds the SQL on the main isolate, sends it to the background isolate, and waits for the result.
Two consequences follow:
- Every query pays a small message-passing cost. A single tiny query is slightly slower than on the main isolate, but the UI cannot stall on it.
- Result rows are copied between isolates. Very large result sets cost memory and copy time, so limit and paginate them as you would anyway.
Opening the database in the background
Here is an explicit setup using path_provider. LazyDatabase delays the file lookup and isolate start until the first query, because finding the directory is asynchronous.
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
QueryExecutor openBackgroundConnection() {
return LazyDatabase(() async {
final dir = await getApplicationDocumentsDirectory();
final file = File(p.join(dir.path, 'app.sqlite'));
return NativeDatabase.createInBackground(file);
});
}Then use it as the default executor in the database class:
AppDatabase([QueryExecutor? executor])
: super(executor ?? openBackgroundConnection());If you use drift_flutter, driftDatabase(name: 'app') already handles the directory lookup for you. It also exposes options for the native platforms through DriftNativeOptions. Check the drift_flutter documentation for your installed version to see how it opens the file, because the defaults have changed between releases.
Sharing one database between isolates
Sometimes your app has more than one isolate that needs the database. Examples are a sync worker started with Isolate.run, a compute call, or a background service. Opening the same SQLite file separately in each isolate is risky. Each connection has its own prepared statements and its own view of changes, and drift cannot tell your other connections that a table changed. Your watch() streams would then go stale after a write from the other isolate.
Drift solves this by letting several isolates connect to one connection owner. Writes from any isolate then reach every stream. With drift_flutter, you can turn this on with an option:
import 'package:drift_flutter/drift_flutter.dart';
QueryExecutor openSharedConnection() {
return driftDatabase(
name: 'app',
native: const DriftNativeOptions(shareAcrossIsolates: true),
);
}When sharing is on, a second isolate can obtain a connection to the same database instead of opening its own file handle. The exact API for connecting from another isolate depends on your drift version, so follow the "Isolates" page in the drift documentation for the version you installed.
Running a heavy job with computeWithDatabase
For one-off heavy work, such as importing a large file, you do not need to manage isolates yourself. Recent drift versions provide computeWithDatabase. It starts a short-lived isolate, connects it to your existing database, runs your function there, and returns the result.
Future<void> importTitles(AppDatabase db, List<String> titles) {
return db.computeWithDatabase(
computation: (bg) async {
await bg.batch((batch) {
batch.insertAll(bg.todoItems, [
for (final title in titles) TodoItemsCompanion.insert(title: title),
]);
});
},
connect: (connection) => AppDatabase(connection),
);
}Points to notice:
- The
computationclosure receives its ownAppDatabaseinstance, namedbghere. Use only that instance inside the closure. - The closure must not capture
db, aBuildContext, a widget, or any object that cannot be sent to another isolate. Capturing such an object throws at runtime when the closure is sent. Thetitleslist is fine because it is plain data. - The
connectfunction builds a database object around the connection the new isolate receives. That is why your constructor must accept aQueryExecutor. - Writes made by the computation notify
watch()streams on the main isolate, so the UI updates as the import progresses.
Common errors
- "Illegal argument in isolate message". The closure you sent captured something that is not sendable, such as a database, a controller, or
thisfrom a widget state. Move the function to a top-level function or astaticmethod and pass only plain data. database is lockederrors. Two separate connections to one file are writing at the same time. Use a shared connection instead of opening the file twice.- Stale streams after a write from another isolate. The writing isolate used its own file connection. Route it through the shared connection so drift can announce table changes.
- Tests that hang or leave files behind. Keep tests on
NativeDatabase.memory(). It runs on the test isolate, which is simple to debug and needs no cleanup beyonddb.close(). - Forgetting to close. A background isolate keeps running until the connection is closed. Call
db.close()when you dispose of a database you created yourself.
Choosing in practice
Start with createInBackground, or driftDatabase, which is the default in most apps. It costs one extra isolate and keeps the main isolate free of SQLite calls. Move to a shared connection only when a second isolate has to read or write. Use computeWithDatabase for isolated heavy jobs. Keep the in-memory executor for tests.
Exercise
Your app imports 20,000 rows from a downloaded file. You wrote the import as a function that opens its own NativeDatabase(file) inside Isolate.run. The import works, but the todo list on screen does not update until the app restarts. Why does this happen, and what would you change?
Show answer
The import isolate has its own separate connection to the file, so the main isolate's drift instance never learns which tables changed, and its watch() streams do not re-run. Replace the second connection with one the main database controls: call db.computeWithDatabase(...) with a computation that uses the provided database, or share the connection across isolates. Writes then pass through drift's change tracking, and the streams update. Pass only plain data, such as the parsed rows, into the closure.
Exercise
Why does a drift Future returned by a query on a plain NativeDatabase(file) not guarantee a smooth UI, even though you used await?
Show answer
await only suspends the calling function. The SQLite call underneath is synchronous FFI running on the same isolate, so a slow statement blocks frame drawing until it finishes. A background connection runs SQLite on another isolate, so the main isolate stays free.