Sub topic 15
Structuring Larger Apps with DAOs
This chapter assumes that you know Dart classes, async and await, Drift tables, generated row types, and basic CRUD queries. It focuses on data access objects, or DAOs.
A DAO is a Dart class that groups database operations for one part of an application. Instead of placing every query inside AppDatabase, you can give related queries to a DAO. The database class then owns the connection and schema, while each DAO owns a focused set of queries.
| Class | Main responsibility |
|---|---|
| `AppDatabase` | Opens the database and declares tables and DAOs |
| `TodoDao` | Inserts, reads, and watches to-do items |
| `TodoItem` | Represents one row returned from a query |
Create a DAO
Annotate a DAO with @DriftAccessor. The tables list gives the DAO access to generated table properties such as todoItems. Drift generates a mixin that connects the DAO to the database accessor.
import 'package:drift/drift.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)();
}
@DriftAccessor(tables: [TodoItems])
class TodoDao extends DatabaseAccessor<AppDatabase>
with _$TodoDaoMixin {
TodoDao(super.db);
Future<int> add(String title) {
return into(todoItems).insert(
TodoItemsCompanion.insert(title: title),
);
}
Stream<List<TodoItem>> watchOpen() {
return (select(todoItems)
..where((table) => table.isDone.equals(false))
..orderBy([
(table) => OrderingTerm.desc(table.createdAt),
]))
.watch();
}
Future<bool> markDone(TodoItem item) {
return update(todoItems).replace(
item.copyWith(isDone: true),
);
}
Future<int> deleteCompleted() {
return (delete(todoItems)
..where((table) => table.isDone.equals(true)))
.go();
}
}
@DriftDatabase(
tables: [TodoItems],
daos: [TodoDao],
)
class AppDatabase extends _$AppDatabase {
AppDatabase(super.executor);
@override
int get schemaVersion => 1;
}The @DriftDatabase annotation registers TodoDao. After adding or changing the DAO, run code generation:
dart run build_runner buildThe generated _$TodoDaoMixin supplies the database connection used by the DAO. The TodoDao methods return domain-specific operations such as add, watchOpen, and markDone. Callers do not need to know how the query is constructed.
Use the DAO from application code
Create one database instance and access its DAO through the generated getter. Drift normally names that getter after the class in lower camel case, so TodoDao becomes todoDao.
final db = AppDatabase(openDatabaseConnection());
final todoDao = db.todoDao;
await todoDao.add('Review the migration');
final openItems = todoDao.watchOpen();A widget, repository, or state-management component can subscribe to watchOpen() without containing SQL-like filtering or ordering logic.
DAO boundaries and trade-offs
A small application can use one DAO for all tables. As the application grows, group queries by feature or aggregate. An aggregate is a set of related data that is changed and read together.
Good DAO boundaries usually have these properties:
- Methods describe useful operations rather than exposing arbitrary query construction.
- Related tables and queries stay together.
- The DAO returns typed rows, records, or small result objects.
- Transactions remain visible when several writes must succeed together.
- Tests can construct the database with an in-memory executor.
Exercise
Why should a feature call todoDao.watchOpen() instead of constructing the filtered query in a widget?
Show answer
The DAO centralizes the query, keeps the widget focused on presentation, and lets the query be reused and tested independently.