Sub topic 7
Create, read, update, and delete with drift
Assume you have basic Dart and Flutter knowledge, understand Future and Stream, and have already created the AppDatabase and TodoItems table from the previous chapters. The examples below go inside AppDatabase.
Drift maps SQL operations to typed Dart methods. The table object, todoItems, describes the table. The generated TodoItem class represents a row that was read. A TodoItemsCompanion represents values for an insert or partial update.
The CRUD operations
CRUD means create, read, update, and delete:
| Operation | Drift method | Result |
|---|---|---|
| Create | `insert` | New row ID |
| Read | `select` | One or more typed rows |
| Update | `update` | Whether a row changed |
| Delete | `delete` | Number of deleted rows |
A basic set of database methods looks like this:
// Add these methods inside AppDatabase.
Future<int> addItem(String title) {
return into(todoItems).insert(
TodoItemsCompanion.insert(title: title),
);
}
Future<List<TodoItem>> allItems() {
return select(todoItems).get();
}
Future<bool> updateItem(TodoItem item) {
return update(todoItems).replace(item);
}
Future<int> deleteItem(int id) {
return (delete(todoItems)
..where((table) => table.id.equals(id)))
.go();
}into(todoItems) creates an insert statement. TodoItemsCompanion.insert requires the fields that must be supplied. The database supplies id, isDone, and createdAt because the table definition gives those columns defaults.
select(todoItems).get() executes the query immediately. It returns a Future<List<TodoItem>>, so call it with await from an asynchronous method.
replace uses the row's primary key to find the existing record. It writes all columns from the TodoItem value. It returns true when a row was updated.
delete does not run until you call go(). The where clause limits deletion to the requested ID. Without a where clause, the statement would delete every row.
Filtering and changing one field
You can add conditions and ordering to a select query:
Future<List<TodoItem>> openItems() {
return (select(todoItems)
..where((table) => table.isDone.equals(false))
..orderBy([
(table) => OrderingTerm.asc(table.createdAt),
]))
.get();
}
Future<int> markDone(int id) {
return (update(todoItems)
..where((table) => table.id.equals(id)))
.write(
const TodoItemsCompanion(
isDone: Value(true),
),
);
}The Value wrapper tells drift that isDone should be written. A companion can omit other columns, so this update changes only one field.
Common errors
- Calling
delete(todoItems).go()without a condition removes all rows. - Using
replacewith a row whose ID is not present updates nothing. - Forgetting
awaitleaves you with aFuture, not the query result. - Using a nullable companion value incorrectly can write
NULLwhen you meant to leave a column unchanged.
Exercise
Which method deletes only the item whose ID is 7?
Show answer
(delete(todoItems)..where((table) => table.id.equals(7))).go()