Sub topic 10
Type-safe databases with drift
Prerequisites and the main idea
This chapter assumes you know Dart classes, null safety, Future, async and await, and the basic sqflite approach to SQLite.
Drift is a type-safe database layer for Flutter. It uses SQLite underneath, but it lets you describe tables and queries in Dart. Code generation then creates row classes, insert companions, and query results. The compiler can catch many mistakes before the app runs.
With sqflite, a query often returns Map<String, Object?>. You must remember column names and cast values yourself. With drift, a query against the notes table returns generated Note objects. This reduces string-based errors, but it adds generated files and a build step.
Define a table and database
Add drift, sqlite3_flutter_libs, and path_provider to pubspec.yaml. Add drift_dev and build_runner under dev_dependencies. Then create a database file:
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
part 'app_database.g.dart';
class Notes extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text()();
TextColumn get body => text().nullable()();
BoolColumn get pinned =>
boolean().withDefault(const Constant(false))();
}
@DriftDatabase(tables: [Notes])
class AppDatabase extends _$AppDatabase {
AppDatabase(super.connection);
@override
int get schemaVersion => 1;
Future<List<Note>> readNotes() {
return select(notes).get();
}
Future<int> addNote(String title, String? body) {
return into(notes).insert(
NotesCompanion.insert(
title: title,
body: Value(body),
),
);
}
Future<int> removeNote(int id) {
return (delete(notes)..where((note) => note.id.equals(id))).go();
}
}
Future<AppDatabase> openAppDatabase() async {
final directory = await getApplicationDocumentsDirectory();
final databaseFile = p.join(directory.path, 'app.sqlite');
return AppDatabase(NativeDatabase.createInBackground(databaseFile));
}The part statement refers to generated Dart code. Generate it after creating the file:
dart run build_runner build --delete-conflicting-outputsNotes describes the SQLite table. Note is a generated row class. NotesCompanion represents values used when inserting or updating a row. Nullable columns require Value(null) in a companion so drift can distinguish “set this to null” from “do not change this field.”
Queries and migrations
Drift builds queries from Dart expressions:
Future<List<Note>> searchNotes(AppDatabase db, String title) {
return (db.select(db.notes)
..where((note) => note.title.equals(title))
..orderBy([(note) => OrderingTerm.desc(note.id)]))
.get();
}
Future<void> pinNote(AppDatabase db, int id) {
await (db.update(db.notes)..where((note) => note.id.equals(id))).write(
const NotesCompanion(pinned: Value(true)),
);
}The title value is bound as a parameter. Do not construct SQL by joining user input into a string.
When the schema changes, increase schemaVersion and describe the upgrade:
@override
int get schemaVersion => 2;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (Migrator m) => m.createAll(),
onUpgrade: (Migrator m, int from, int to) async {
if (from < 2) {
await m.addColumn(notes, notes.pinned);
}
},
);New installs run onCreate. Existing installs run the needed upgrade steps. Keep each version change in order so users who skip several app releases can still migrate safely.
Trade-offs and common errors
Use drift when the app has several related tables, joins, migrations, or queries that should be checked by the compiler. It is often more structure than a few settings require. shared_preferences is simpler for small key-value settings, while drift is better for searchable structured data.
Common mistakes include forgetting to regenerate code, changing a table without adding a migration, and assuming a nullable column behaves like a non-nullable one. Test migrations with a database created at each older version, not only with a fresh database.
> callout warning > Generated code is part of the build process, not a hand-edited source file. Change the table or query definition, then run the generator again.
Exercise
Why does drift need a migration when a new column is added to an existing table?
Show answer
Existing user databases already have the old schema. The migration describes how to change those databases without deleting their stored rows.