Sub topic 15
Structuring larger apps with DAOs
This chapter assumes you have a working drift database with tables, generated code, and watch() queries, as covered in the earlier chapters. You should also be comfortable with Dart part files and with the transaction method.
Why split the database class
In the earlier chapters every query lived inside AppDatabase. That works for a small app. As the app grows, the class collects dozens of methods for unrelated features, and the generated file for the whole schema becomes the only place anything can be found.
A DAO (data access object) is a class that groups the queries for one area of the app. Drift implements it as a DatabaseAccessor. A DAO does not own a connection. It borrows the one from the database, so every DAO shares the same SQLite file, the same transactions, and the same stream invalidation.
Tables in their own file
DAO files must import the database, and the database must import the DAOs. Dart allows circular imports, but keeping the table classes in a separate file makes the layout clearer. The tables here add a Categories table and a nullable foreign key on TodoItems.
// lib/tables.dart
import 'package:drift/drift.dart';
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 50)();
}
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)();
IntColumn get categoryId =>
integer().nullable().references(Categories, #id)();
}Writing a DAO
A DAO is annotated with @DriftAccessor. Its tables list names the tables the DAO can touch. Drift generates a mixin that adds a getter for each listed table, so todoItems and categories work inside the class as they did in the database class.
// lib/daos/todo_dao.dart
import 'package:drift/drift.dart';
import '../database.dart';
import '../tables.dart';
part 'todo_dao.g.dart';
@DriftAccessor(tables: [TodoItems, Categories])
class TodoDao extends DatabaseAccessor<AppDatabase> with _$TodoDaoMixin {
TodoDao(super.attachedDatabase);
Future<int> addItem(String title, {int? categoryId}) =>
into(todoItems).insert(
TodoItemsCompanion.insert(
title: title,
categoryId: Value(categoryId),
),
);
Future<List<TodoItem>> allItems() => select(todoItems).get();
Stream<List<TodoItem>> watchOpenItems() {
return (select(todoItems)
..where((t) => t.isDone.equals(false))
..orderBy([(t) => OrderingTerm.desc(t.createdAt)]))
.watch();
}
Stream<List<(TodoItem, Category?)>> watchWithCategory() {
final query = select(todoItems).join([
leftOuterJoin(categories, categories.id.equalsExp(todoItems.categoryId)),
]);
return query.watch().map((rows) => rows
.map((row) => (row.readTable(todoItems), row.readTableOrNull(categories)))
.toList());
}
}The Value(categoryId) wrapper matters. A nullable column is optional in TodoItemsCompanion.insert, and Value(null) writes an explicit NULL, while leaving the argument out lets the column default apply.
A second DAO covers the categories. It lists TodoItems as well, because deleting a category must detach its to-dos.
// lib/daos/category_dao.dart
import 'package:drift/drift.dart';
import '../database.dart';
import '../tables.dart';
part 'category_dao.g.dart';
@DriftAccessor(tables: [Categories, TodoItems])
class CategoryDao extends DatabaseAccessor<AppDatabase>
with _$CategoryDaoMixin {
CategoryDao(super.attachedDatabase);
Future<int> addCategory(String name) =>
into(categories).insert(CategoriesCompanion.insert(name: name));
Stream<List<Category>> watchAll() => select(categories).watch();
Future<void> deleteCategory(int id) => transaction(() async {
await (update(todoItems)..where((t) => t.categoryId.equals(id)))
.write(const TodoItemsCompanion(categoryId: Value(null)));
await (delete(categories)..where((c) => c.id.equals(id))).go();
});
}transaction is available on every DAO. If either statement throws, both are rolled back.
Registering the DAOs
The database class lists its DAOs in the daos argument. Drift then generates one getter per DAO, named after the class with a lowercase first letter.
// lib/database.dart
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
import 'daos/category_dao.dart';
import 'daos/todo_dao.dart';
import 'tables.dart';
part 'database.g.dart';
@DriftDatabase(
tables: [TodoItems, Categories],
daos: [TodoDao, CategoryDao],
)
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
}Run the generator again so that database.g.dart, todo_dao.g.dart, and category_dao.g.dart are all produced.
dart run build_runner buildThe row classes TodoItem and Category and the companions are generated into database.g.dart. That is why each DAO file imports database.dart.
Calling DAOs from the UI
Widgets reach a DAO through the database instance, for example db.todoDao.watchOpenItems(). Pass the database down with constructor arguments or your dependency injection package. A widget that only needs one feature can take the DAO itself, which makes its dependencies obvious.
class OpenItemsList extends StatelessWidget {
const OpenItemsList({super.key, required this.dao});
final TodoDao dao;
@override
Widget build(BuildContext context) {
return StreamBuilder<List<TodoItem>>(
stream: dao.watchOpenItems(),
builder: (context, snapshot) {
final items = snapshot.data ?? const [];
return ListView(
children: [for (final item in items) ListTile(title: Text(item.title))],
);
},
);
}
}Testing a DAO
DAOs need no special test setup. Build an in-memory database and use the DAO getter.
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo_app/database.dart';
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() => db.close());
test('deleting a category keeps its items', () async {
final categoryId = await db.categoryDao.addCategory('Work');
await db.todoDao.addItem('Write report', categoryId: categoryId);
await db.categoryDao.deleteCategory(categoryId);
final items = await db.todoDao.allItems();
expect(items.single.categoryId, isNull);
});
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `_$TodoDaoMixin` is undefined | The DAO's `.g.dart` was not generated or has no `part` line | Add `part 'todo_dao.g.dart';` and rerun `build_runner` |
| `db.todoDao` does not exist | The DAO is missing from `daos:` on `@DriftDatabase` | Add it and regenerate |
| Table getter such as `categories` not found in a DAO | The table is not in that DAO's `tables:` list | List every table the DAO queries |
| Stream does not update after a write in another DAO | A second `AppDatabase` instance was created | Share one instance per app |
The last row deserves attention. Streams are invalidated by the database object that performed the write. Two instances of AppDatabase pointing at the same file do not notify each other by default, so create one instance and pass it around.
Choosing boundaries
Split by feature or by aggregate, not by query type. A TodoDao holding reads and writes for to-dos is easier to navigate than separate ReadDao and WriteDao classes. If an operation spans several tables, as deleteCategory does, put it in the DAO that owns the intent and list every table it touches. For work that crosses many features, a plain repository class that calls several DAOs inside db.transaction keeps each DAO small.
Exercise
You add a SettingsDao with @DriftAccessor(tables: [Settings]) and run build_runner, but db.settingsDao does not compile. What did you most likely forget, and what are two other places that must be correct for the DAO to work?
Show answer
The DAO is probably missing from the daos list in @DriftDatabase, so no settingsDao getter is generated. The DAO file also needs a part 'settings_dao.g.dart'; line with the class using with _$SettingsDaoMixin, and the Settings table must be listed in the database's tables list so the schema contains it. Rerun dart run build_runner build after fixing these.