Sub topic 5
Creating the database class and opening it
This chapter assumes you know basic Dart classes, async and await, Flutter project commands, and the purpose of a relational database table. It also assumes that your tables are already defined and that drift code generation is configured. The generated file does not exist until you run build_runner.
The database class
A drift database class connects your Dart table definitions to a SQLite database. The @DriftDatabase annotation lists the tables that belong to this database. Drift then generates a parent class named _$AppDatabase.
Create lib/data/database.dart:
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
DateTimeColumn get createdAt =>
dateTime().withDefault(currentDateAndTime)();
}
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}QueryExecutor is drift's abstraction for something that can execute SQL queries. The optional constructor parameter is useful because production code can open the normal on-device database, while tests can provide an in-memory executor.
When no executor is supplied, driftDatabase(name: 'app') creates or opens a SQLite database managed by the Flutter platform integration. The name identifies the database. Use a stable name so the app reopens the same file after it restarts.
The schemaVersion identifies the shape of the database. A new installation starts at version 1. Later, when you change a table, increase this number and add a migration. Do not change the number without describing how existing data should be upgraded.
Generating and opening the connection
Add drift and its generator, then generate the supporting code:
flutter pub add drift drift_flutter
flutter pub add dev:drift_dev dev:build_runner
dart run build_runner buildThe generator reads database.dart and creates database.g.dart. That file contains the generated superclass, table accessors, row classes, and query support. If you change a table or annotation, run the generator again. During development, watch can regenerate code after each source change:
dart run build_runner watchCreate one AppDatabase instance and share it with the parts of the application that use the database. Opening many instances can create unnecessary connections and makes lifecycle management harder.
Supplying a different executor
Dependency injection means passing a dependency into a class instead of constructing it inside every method. The constructor supports this pattern. Production code can use the default executor, while tests can pass NativeDatabase.memory() for an isolated database. This keeps database tests fast and prevents test data from changing the user's files.
Exercise
Why does AppDatabase accept an optional QueryExecutor?
Show answer
It uses the normal on-device database by default, but it can receive an in-memory or otherwise configured executor for tests and other environments.