Sub topic 17
Moving Database Work off the Main Isolate
This chapter assumes that you know Dart isolates, Future, Stream, and the AppDatabase class from earlier chapters. The goal is to keep SQLite work from blocking Flutter’s main isolate, which is responsible for drawing frames and responding to input.
Why use a background isolate?
An isolate is an independent Dart execution context with its own memory. The main isolate runs Flutter’s UI. A database operation that performs a large query, migration, or batch write can use CPU time and delay frames if it runs there.
Drift can run its SQLite executor in a background isolate. Your UI code still calls typed database methods, but Drift sends those requests to the worker isolate.
The application does not directly share Dart objects between isolates. Drift serializes requests and results across the isolate boundary.
Using drift_flutter
For a Flutter application, driftDatabase is the simplest option. It chooses a suitable database location and uses a background isolate on supported native platforms.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}Create one application-level database instance and pass it to the parts of the app that need it:
void main() {
WidgetsFlutterBinding.ensureInitialized();
final database = AppDatabase();
runApp(MyApp(database: database));
}Calls such as database.allItems() return a Future. A watched query returns a Stream, so the UI can continue using FutureBuilder and StreamBuilder as usual.
| Concern | Main-isolate database | Background-isolate database |
|---|---|---|
| UI responsiveness | Large work can delay frames | Database work is separated |
| API used by widgets | Futures and streams | The same Futures and streams |
| Data sharing | Direct Dart objects | Serialized messages |
| Best use | Small, simple operations | Production apps and heavier work |
Explicit native executors
If you need to control the database file yourself, Drift also provides a background native executor:
import 'dart:io';
import 'package:drift/native.dart';
AppDatabase openDatabase(File file) {
final executor = NativeDatabase.createInBackground(file);
return AppDatabase(executor);
}This approach is for native platforms. Web applications use a different storage and worker model, so do not assume that dart:io or NativeDatabase is available there.
Close the database when its owning component is permanently disposed:
@override
void dispose() {
database.close();
super.dispose();
}Do not close a shared database from a short-lived screen. The next screen may still need it.
Common failure modes
- Opening the same SQLite file with different database configurations can cause lock contention.
- Calling database methods before Flutter initialization can fail when the executor needs platform services.
- Passing a database instance between isolates is not valid. Create or connect to it through Drift’s isolate support.
- Background execution does not make a badly filtered query fast. Add suitable indexes and limits.
Exercise
A screen creates and closes its own AppDatabase in dispose(), but another screen uses the same database instance. What problem can this cause?
Show answer
The first screen can close the shared connection while the second screen still needs it. Give the database a longer-lived owner, such as an application repository or provider.