Sub topic 4
Generating code with build_runner
This chapter assumes you can write Dart classes and annotations, you have added drift, drift_flutter, drift_dev and build_runner to a project, and you have defined a Table class like TodoItems. Here you learn what the generator produces, how to run it, and how to fix the errors that come up most often.
Why drift needs generated code
You describe tables as Dart classes that extend Table. Dart can't turn those descriptions into typed row classes at compile time, because it has no macros or reflection in Flutter builds. A code generator reads your source and writes the missing Dart files before you compile.
build_runner is the tool that runs generators. drift_dev is the generator that understands drift's annotations. You run build_runner, and build_runner calls drift_dev.
Both are dev dependencies. Neither ships in your app. Only the generated .g.dart file does.
What gets generated
For each @DriftDatabase class, the generator writes a part file next to your source. For database.dart that file is database.g.dart. It contains:
| Generated item | Example name | Purpose |
|---|---|---|
| Database base class | `_$AppDatabase` | Your `AppDatabase` extends it. It holds the table getters such as `todoItems`. |
| Table implementation | `$TodoItemsTable` | The runtime object that knows column types and SQL names. |
| Row class | `TodoItem` | An immutable object returned by `select`. |
| Companion class | `TodoItemsCompanion` | A value wrapper used for inserts and partial updates. |
Drift derives the row name by singularizing the table class name, so TodoItems becomes TodoItem. To pick a different name, annotate the table with @DataClassName:
import 'package:drift/drift.dart';
@DataClassName('Todo')
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
}With this annotation, select(todoItems).get() returns List<Todo>. The companion keeps the name TodoItemsCompanion.
The part directive links your code to the output
The generated file is a Dart part, which means it is a piece of your library and not a separate library. Your source must declare it with a part line. Without that line the generator has nothing to attach to.
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 the first build, your editor will underline _$AppDatabase and the part URI as errors. That is expected, because the file they point to doesn't exist yet.
The part filename must match your source filename with .g.dart in place of .dart. If your file is app_database.dart, write part 'app_database.g.dart';.
Running the generator
You have two commands. Run both from the project root, where pubspec.yaml lives.
# One-off build
dart run build_runner build
# Rebuild automatically whenever a source file changes
dart run build_runner watchUse build in scripts and CI. Use watch while you edit tables, so the generated code stays current as you work. The first run is slow, often tens of seconds, because build_runner analyzes your whole package. Later runs are incremental and much faster.
Stop watch with Ctrl+C. If you forget it is running, it keeps rebuilding in the background and can hold a lock on the build directory.
How a build flows
When to regenerate
Regenerate after any change that affects the schema or the generated API. That includes:
- Adding, removing or renaming a table or column.
- Changing a column's type, nullability or default.
- Adding
@DataClassName,@UseRowClass, or other drift annotations. - Adding or removing a table in the
tables:list of@DriftDatabase.
You don't need to regenerate after changing method bodies, such as a new select query written in Dart inside AppDatabase. Those methods are ordinary Dart code that you wrote, not generated output.
Changing a column also changes the on-device schema. Regenerating updates only the Dart code. To make existing installs match, bump schemaVersion and write a migration. That is a later chapter.
Fixing common errors
"Target of URI hasn't been generated"
The .g.dart file does not exist. Either you haven't run the build, or the build failed. Run dart run build_runner build and read the output for the first error.
"Conflicting outputs"
build_runner refuses to overwrite files it did not create, or files left from a different configuration. It prints a message about conflicting outputs. Rerun with the delete flag:
dart run build_runner build --delete-conflicting-outputsThis deletes the stale generated files and writes new ones. Only generated files are affected, so your source files are safe.
The build succeeds but nothing is generated
Check these causes in order:
- The class has no
@DriftDatabaseannotation, or the annotation import is missing. - The
partdirective is absent or names the wrong file. drift_devis missing fromdev_dependencies.- The file lives outside
lib/, in a folder the builder does not scan by default.
Errors that mention a missing name such as `_$AppDatabase`
If these remain after a successful build, restart the Dart analysis server in your editor. It sometimes keeps a stale view of the part file.
Odd results after a failed build
Delete the cached build state, then build again:
dart run build_runner clean
dart run build_runner buildThe clean command removes the .dart_tool/build cache and the generated outputs build_runner tracks, so the next build starts from scratch.
Version control and CI
Teams handle generated files in two ways.
- Commit them. A fresh checkout compiles immediately, and code review shows how a schema change alters the generated output. The cost is large diffs and occasional merge conflicts in generated files. When that happens, resolve the source files, then regenerate instead of merging the
.g.darttext. - Ignore them. Add
*.g.dartto.gitignoreand rundart run build_runner buildas the first step of CI and local setup. Diffs stay small, but every build needs the extra step, and a forgotten step produces the "hasn't been generated" error.
Either approach works. Pick one for the whole team and write it in the README. In CI, add --delete-conflicting-outputs so a leftover cache can't fail the job.
Where this leaves you
You can now turn table definitions into typed code, and you know the three failure patterns: a missing part line, a stale or conflicting output, and a missing dependency. The next chapter uses the generated AppDatabase to open a connection and run the first queries.
Exercise
After you rename the column title to name in TodoItems, your editor still shows title as a valid field on TodoItem, and dart run build_runner build reports conflicting outputs. What command do you run, and which two files or settings do you check if the problem persists?
Show answer
Run dart run build_runner build --delete-conflicting-outputs to remove the stale database.g.dart and regenerate it, so TodoItem exposes name. If the problem persists, check that the part 'database.g.dart'; line matches the source filename, and restart the Dart analysis server so the editor stops using the old generated file. Because the column rename changes the on-device schema, you also need to raise schemaVersion and add a migration for existing installs.