Sub topic 7
Create, read, update, and delete
This chapter assumes you have a working AppDatabase with a TodoItems table and the generated database.g.dart file, as built in the previous chapters. You should also be comfortable with Future and async/await.
Drift exposes each of the four basic operations as a builder. You start from a method on the database (into, select, update, delete), optionally refine it, then run it with a terminating call such as get(), write(), or go().
Create
into(table).insert(...) takes a companion and returns the new row's integer primary key. The generated TodoItemsCompanion.insert constructor requires only the columns that have no default and are not nullable. Here that is title. The columns id, isDone, and createdAt are filled in by SQLite or by their declared defaults.
// Inside AppDatabase
Future<int> addItem(String title) =>
into(todoItems).insert(TodoItemsCompanion.insert(title: title));
Future<TodoItem> addItemAndGet(String title) =>
into(todoItems).insertReturning(TodoItemsCompanion.insert(title: title));
Future<int> saveItem(TodoItemsCompanion entry) =>
into(todoItems).insertOnConflictUpdate(entry);insertReturninggives you the full row, including generated values such asidandcreatedAt, without a second query.insertOnConflictUpdateis an upsert. If a row with the same primary key or unique value exists, it is updated instead of causing an error.
The withLength(min: 1, max: 100) constraint on title is checked by drift's generated validation. Inserting an empty title throws an exception at runtime. The compiler does not catch it.
Read
select(table).get() runs the query once and returns a Future<List<Row>>. Two variants return a single row.
// Inside AppDatabase
Future<List<TodoItem>> allItems() => select(todoItems).get();
Future<TodoItem?> findItem(int id) =>
(select(todoItems)..where((t) => t.id.equals(id))).getSingleOrNull();
Future<TodoItem> requireItem(int id) =>
(select(todoItems)..where((t) => t.id.equals(id))).getSingle();The .. cascade operator calls where on the statement and then returns the statement itself, so you can pass it on. That is why the expression needs the outer parentheses. Without them, you would be calling getSingleOrNull() on the result of where, which returns void.
getSingle() throws a StateError if there are zero rows or more than one. Use getSingleOrNull() when the row might not exist. It still throws if more than one row matches.
A row object such as TodoItem is immutable. It holds values as they were when the query ran and does not update itself if the table changes.
Update
Drift offers two update styles, and they behave differently.
Replace the whole row
replace writes every column of a row object to the row with the same primary key.
// Inside AppDatabase
Future<bool> updateItem(TodoItem item) =>
update(todoItems).replace(item);
Future<bool> toggleDone(TodoItem item) =>
update(todoItems).replace(item.copyWith(isDone: !item.isDone));The generated data class has a copyWith method, so you can change one field and keep the rest. replace returns true if a row was updated. Because it overwrites every column, a stale row object can silently undo changes made elsewhere since you read it.
Write only some columns
write updates only the columns you mark as present in a companion. It uses a where clause to pick the rows and returns the number of rows changed.
// Inside AppDatabase
Future<int> markDone(int id) =>
(update(todoItems)..where((t) => t.id.equals(id)))
.write(const TodoItemsCompanion(isDone: Value(true)));
Future<int> renameItem(int id, String title) =>
(update(todoItems)..where((t) => t.id.equals(id)))
.write(TodoItemsCompanion(title: Value(title)));Columns left out of the companion default to Value.absent(), which means "do not touch". This is how a companion differs from a row object.
Absent versus null
For a nullable column such as note, the two values mean different things.
| Companion value | Effect in an update |
|---|---|
| `Value.absent()` | Column is left unchanged |
| `Value(null)` | Column is set to `NULL` |
| `Value('text')` | Column is set to `'text'` |
Mixing up Value.absent() and Value(null) is a common cause of notes that never clear, or that clear unexpectedly.
Delete
delete(table) works like update. A where clause limits the rows, and go() runs the statement and returns the number of rows deleted.
// Inside AppDatabase
Future<int> deleteItem(int id) =>
(delete(todoItems)..where((t) => t.id.equals(id))).go();
Future<int> deleteDone() =>
(delete(todoItems)..where((t) => t.isDone.equals(true))).go();
Future<int> clearAll() => delete(todoItems).go();Checking the return value tells you whether anything happened. A result of 0 from deleteItem means the id did not exist. No exception is thrown.
Many rows at once
Running hundreds of separate inserts is slow because each one is its own statement. A batch sends them together.
// Inside AppDatabase
Future<void> addMany(List<String> titles) {
return batch((b) {
b.insertAll(
todoItems,
[for (final t in titles) TodoItemsCompanion.insert(title: t)],
);
});
}A batch is also atomic: if one statement fails, none of the changes are kept. Batches cannot return values from individual statements. Use insertReturning in a loop, or a transaction, when you need the results.
Using the methods from a widget
Call database methods from event handlers and await them. You do not need setState if the list is driven by a watch() stream, which a later chapter covers.
import 'package:flutter/material.dart';
class AddItemButton extends StatelessWidget {
const AddItemButton({super.key, required this.db});
final AppDatabase db;
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () async {
try {
await db.addItem('New task');
} on Exception catch (e) {
if (!context.mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Could not save: $e')));
}
},
child: const Icon(Icons.add),
);
}
}Common mistakes
- Forgetting the parentheses around
select(...)..where(...)before callingget(). - Passing a row object where a companion is required, or the reverse. Rows are for reading and
replace. Companions are forinsertandwrite. - Using
replacewith a row read long ago, which overwrites newer data. - Treating
0rows affected as success. - Running
writeorgowith nowhereclause.
Exercise
You want to set the note column of the item with id 7 to NULL and leave every other column unchanged. Write the update, and say why TodoItemsCompanion(note: Value.absent()) would not work.
Show answer
(update(todoItems)..where((t) => t.id.equals(7))).write(const TodoItemsCompanion(note: Value(null))); Using Value.absent() tells drift to skip the column, so the old note stays in the database. Value(null) is the explicit request to store NULL.
Exercise
What is the difference between update(todoItems).replace(item) and update(todoItems).write(companion) when two parts of the app edit the same row?
Show answer
replace overwrites every column with the values in the row object, so a stale object can erase changes made after it was read. write changes only the columns present in the companion, so edits to other columns are preserved.