Use analyzed snippet for DAOs page

Related to https://github.com/simolus3/drift/pull/3705
This commit is contained in:
Simon Binder
2025-11-07 17:01:44 +01:00
parent 9db73b545a
commit e5149c6d08
3 changed files with 109 additions and 103 deletions
+2 -23
View File
@@ -7,28 +7,7 @@ When you have a lot of queries, putting them all into one class might become
tedious. You can avoid this by extracting some queries into classes that are
available from your main database class. Consider the following code:
```dart
part 'todos_dao.g.dart';
<Snippet href="/lib/src/snippets/setup/todos_dao.dart" name="snippet" />
// the _TodosDaoMixin will be created by drift. It contains all the necessary
// fields for the tables. The <MyDatabase> type annotation is the database class
// that should use this dao.
@DriftAccessor(tables: [Todos])
class TodosDao extends DatabaseAccessor<MyDatabase> with _$TodosDaoMixin {
// this constructor is required so that the main database can create an instance
// of this object.
TodosDao(super.db);
Stream<List<TodoEntry>> todosInCategory(Category? category) {
if (category == null) {
return (select(todos)..where((t) => t.category.isNull())).watch();
} else {
return (select(todos)..where((t) => t.category.equals(category.id)))
.watch();
}
}
}
```
If we now change the annotation on the `MyDatabase` class to `@DriftDatabase(tables: [Todos, Categories], daos: [TodosDao])`
If we now change the annotation on the `AppDatabase` class to `@DriftDatabase(tables: [TodoItems], daos: [TodosDao])`
and re-run the code generation, a generated getter `todosDao` can be used to access the instance of that dao.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,26 @@
import 'package:drift/drift.dart';
import 'database.dart';
// #docregion snippet
part 'todos_dao.g.dart';
// the _TodosDaoMixin will be created by drift. It contains all the necessary
// fields for the tables. The <MyDatabase> type annotation is the database class
// that should use this dao.
@DriftAccessor(tables: [TodoItems])
class TodosDao extends DatabaseAccessor<AppDatabase> with _$TodosDaoMixin {
// this constructor is required so that the main database can create an instance
// of this object.
TodosDao(super.attachedDatabase);
Stream<List<TodoItem>> findTodos(String? contentFilter) {
final query = select(todoItems);
if (contentFilter case final filter?) {
query.where((item) => item.content.contains(filter));
}
return query.watch();
}
}
// #enddocregion snippet