Sub topic 2
Installing drift and the code generator
This chapter covers adding drift to a Flutter project, running the code generator once, and fixing the errors you are most likely to hit. It assumes you can create a Flutter project, edit pubspec.yaml, use the Dart and Flutter command line, and read basic Dart. You don't need to know SQL yet, because later chapters introduce tables and queries.
What you are installing
drift is split into several packages. Each has a separate job, so it helps to know which one belongs in which section of pubspec.yaml.
| Package | Section | Purpose |
|---|---|---|
| `drift` | dependencies | The runtime library: table definitions, query builders, streams, migrations. |
| `drift_flutter` | dependencies | Opens the database on Android, iOS, macOS, Windows, Linux and the web. It bundles the right SQLite setup for each platform. |
| `drift_dev` | dev_dependencies | The code generator. It reads your annotated Dart classes and writes the supporting code. |
| `build_runner` | dev_dependencies | The tool that runs code generators such as `drift_dev`. |
The runtime packages ship inside your app. The generator and build_runner only run on your development machine, which is why they go under dev_dependencies. Putting them in dependencies would not break anything, but it would mislead readers of the file and add packages to the dependency graph that the app never uses.
Adding the packages
Run these commands from the root of your Flutter project, the folder that contains pubspec.yaml.
flutter pub add drift drift_flutter
flutter pub add dev:drift_dev dev:build_runner
dart run build_runner buildThe first command adds the two runtime packages. The second adds the generator and its runner as development-only dependencies. The third runs the generator once.
If you run the third command now, in a project with no drift code yet, it finishes quickly and generates nothing. That is a useful check, because it proves the toolchain resolves and starts before you add any drift code of your own.
What the commands change
After the two pub add commands, your pubspec.yaml should contain entries like these. The version numbers will differ, because pub add picks the newest versions compatible with your SDK constraints.
dependencies:
flutter:
sdk: flutter
drift: ^2.20.0
drift_flutter: ^0.2.0
dev_dependencies:
flutter_test:
sdk: flutter
drift_dev: ^2.20.0
build_runner: ^2.4.0Keep drift and drift_dev on the same minor version. The generator writes code that calls into the runtime library, so a mismatch can produce generated code that does not compile. When you upgrade one, upgrade the other in the same step with flutter pub upgrade drift drift_dev.
How the pieces work together
You write Dart classes that describe your tables and database. You mark the database class with an annotation. The generator reads those files and writes a companion file next to each one, named with the .g.dart suffix. Your source file includes that generated file with a part directive.
The generated file is not a separate library. It is a part of your file, so it can see private members and your file can use the generated classes, such as _$AppDatabase. This is why the next chapters start every database file with part 'database.g.dart'; and why that line is a compile error until the generator has run.
Running the generator
You have two ways to run the generator. They use the same configuration and produce the same output.
dart run build_runner buildruns once and exits. Use it in scripts, in continuous integration, and when you only changed a few files.dart run build_runner watchstays running and regenerates whenever you save a file. Use it while you work on tables, because it avoids repeating the command.
A third option is useful when generation behaves strangely:
dart run build_runner build --delete-conflicting-outputsThe --delete-conflicting-outputs flag removes generated files that conflict with what the build wants to write. You will need it when a stale .g.dart file exists, for example after you pull changes from version control that include generated files or after you rename a source file.
Should you commit generated files?
Teams make different choices here, and both are workable.
- If you commit
.g.dartfiles, a new developer can open the project and run it immediately, and code review shows what changed in generated output. The cost is noisy diffs and merge conflicts in generated code. - If you add
*.g.dartto.gitignore, the repository stays small and conflicts disappear. The cost is that every checkout, and your CI pipeline, must rundart run build_runner buildbefore building the app.
Pick one rule and apply it to the whole project. Mixing the two leads to the stale-file problems described below.
Verifying the installation
A minimal check confirms that everything works end to end. Create lib/database.dart with one table and one database class. The next chapters explain each piece, so for now treat it as a test fixture.
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)();
}
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}Before you run the generator, your editor will show errors on the part line and on _$AppDatabase. That is expected, because those names do not exist yet. Now run the generator:
dart run build_runner buildA successful run prints a summary and writes lib/database.g.dart. The errors in your editor disappear once the analyzer picks up the new file. If they remain, restart the Dart analysis server from your editor.
Common errors and fixes
Most installation problems fall into a short list. The table pairs each symptom with its usual cause.
| Symptom | Likely cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'database.g.dart'` | The generator has not run yet. | Run `dart run build_runner build`. |
| `Classes can only extend other classes` on `_$AppDatabase` | The generated file is missing or failed to generate. | Run the generator and read its output for earlier errors. |
| The part file name does not match | The `part` directive uses a different name than the source file. | If the source is `app_db.dart`, the directive must be `part 'app_db.g.dart';`. |
| `Conflicting outputs were detected` | A stale `.g.dart` file exists. | Run the build with `--delete-conflicting-outputs`. |
| Version solving failed | `drift` and `drift_dev` need different versions of a shared package such as `analyzer`. | Upgrade both together, or upgrade Flutter and Dart to a newer SDK. |
| Generated code fails to compile after an upgrade | `drift` and `drift_dev` versions have drifted apart. | Align both to the same minor version, then rebuild. |
| The build finishes but generates nothing | The file has no `@DriftDatabase` annotation, or the project does not include `build_runner` in its dev dependencies. | Check the annotation and the `pubspec.yaml` entries. |
Reading generator output
When a build fails, scroll up to the first error. Later errors often follow from the first one. A typical cause is a mistake inside a table definition, for example a missing () at the end of a column getter. Fix that and rebuild before you look at anything else.
Platform notes
drift_flutter handles most platform setup for you, but a few points are worth knowing.
- On mobile and desktop it uses a bundled SQLite build, so you don't depend on whichever SQLite version the operating system provides.
- On the web, drift needs extra files, a WebAssembly build of SQLite and a worker script, served alongside your app. Native targets don't need them. If you only target mobile or desktop, you can skip web setup entirely.
- The database file lives in the application's documents directory, so it is private to your app and removed when the app is uninstalled.
Keeping builds fast
Code generation time grows with the number of files build_runner scans. You can limit its scope with a build.yaml file in the project root. This is optional for small projects.
targets:
$default:
builders:
drift_dev:
generate_for:
include:
- lib/database/**With this file, drift_dev only inspects files under lib/database/. If you use this option, put every drift source file in that folder, or the generator will skip it without warning.
Summary of the workflow
- Add
driftanddrift_flutteras dependencies. - Add
drift_devandbuild_runneras dev dependencies. - Write or change tables and the database class.
- Run
dart run build_runner build, or keepwatchrunning. - Fix errors from the first one down, and use
--delete-conflicting-outputsfor stale files.
Exercise
You add a new column to a table, run the app, and the compiler reports that the generated class doesn't have the new column. The .g.dart file is in version control. What are two likely causes, and what do you run to fix it?
Show answer
The generated file is stale because you didn't rerun the generator after editing the table, or a conflicting old output blocked regeneration. Run dart run build_runner build --delete-conflicting-outputs, or keep dart run build_runner watch running so generation happens on every save.
Exercise
Why do drift_dev and build_runner go under dev_dependencies while drift and drift_flutter go under dependencies?
Show answer
drift and drift_flutter are libraries your app calls at runtime, so they ship with it. drift_dev and build_runner only generate code on your machine during development, and the generated output is what ships, so they aren't needed in the built app.
Exercise
Your source file is lib/app_db.dart. What part directive does it need, and what happens if it says part 'database.g.dart'; instead?
Show answer
It needs part 'app_db.g.dart';. The generator names its output after the source file, so with the wrong name the analyzer reports that the target URI doesn't exist, and _$AppDatabase stays undefined even after a successful build.