Sub topic 6
Rows and companions: reading versus writing
This chapter assumes basic Dart, Flutter, async and await, Futures, Streams, and relational database terms such as tables and rows.
Drift generates two important types for each table:
- A row class represents a complete record read from SQLite. For
TodoItems, the generated class isTodoItem. - A companion class represents values being inserted or changed. For
TodoItems, the generated class isTodoItemsCompanion.
The two types have different jobs. A row should describe a complete database record. A companion can describe only the columns you want to write.
| Type | Main use | Typical example |
|---|---|---|
| `TodoItem` | Read a complete row | Display an item in a widget |
| `TodoItemsCompanion` | Insert or partially update values | Change only `isDone` |
Reading complete rows
A select query returns generated row objects. Their fields have Dart types based on the table definition. A non-nullable text column becomes String; a nullable column becomes String?.
// Inside AppDatabase
Future<List<TodoItem>> allItems() {
return select(todoItems).get();
}
Future<TodoItem?> findItem(int id) {
return (select(todoItems)..where((t) => t.id.equals(id))).getSingleOrNull();
}A TodoItem includes every column, including generated values such as the auto-incrementing id and the default createdAt. This makes row objects convenient for displaying data or passing a complete record to another method.
Writing with companions
A companion makes the fields being written explicit. The insert constructor usually accepts required values and lets the database fill columns with defaults.
// Inside AppDatabase
Future<int> addItem(String title) {
return into(todoItems).insert(
TodoItemsCompanion.insert(title: title),
);
}
Future<int> markDone(int id) {
return (update(todoItems)..where((t) => t.id.equals(id))).write(
const TodoItemsCompanion(isDone: Value(true)),
);
}The Value wrapper tells drift that a column has been supplied. A field omitted from a companion is left unchanged during an update. This is why companions are safer for partial updates than constructing a new row manually.
For a full replacement, use a row object:
Future<bool> replaceItem(TodoItem item) {
return update(todoItems).replace(item);
}Use replace only when you have the complete, current row. It writes all columns, so an old row object could overwrite newer changes made elsewhere.
The data flow
Choose a row when you need to read or replace a complete record. Choose a companion when you are inserting a record or changing selected columns.
Exercise
Why is a companion preferable to a row object when marking one to-do item as complete?
Show answer
A companion updates only the isDone column, while a row replacement writes every column and could overwrite newer values with stale data.