Sub topic 9
Watching queries as streams
This chapter covers how watch() turns a one-time query into a live one. You should already know the select, where, and orderBy methods from the earlier chapters. You should also know how Dart Streams and StreamBuilder work, and have a working AppDatabase with a TodoItems table.
From get to watch
Every drift select can end in one of two calls. get() returns a Future with the rows as they are right now. watch() returns a Stream that emits the current rows and then emits again each time the data may have changed.
// One-time snapshot
Future<List<TodoItem>> openOnce() =>
(select(todoItems)..where((t) => t.isDone.equals(false))).get();
// Live result
Stream<List<TodoItem>> openLive() =>
(select(todoItems)..where((t) => t.isDone.equals(false))).watch();The query builder is identical. Only the terminal call differs, so you can move a query from one-shot to reactive without rewriting its filters.
| Terminal call | Returns | Use it when |
|---|---|---|
| `get()` | `Future<List<T>>` | You need the data once, such as an export |
| `getSingle()` | `Future<T>` | Exactly one row must match, otherwise it throws |
| `getSingleOrNull()` | `Future<T?>` | Zero or one row can match |
| `watch()` | `Stream<List<T>>` | The UI shows a list that must stay current |
| `watchSingle()` | `Stream<T>` | You display one row or one aggregate value |
| `watchSingleOrNull()` | `Stream<T?>` | The row may not exist yet, or may be deleted |
How drift knows when to re-run
SQLite has no built-in way to push changes to Dart. Drift fills the gap itself. Each query records the set of tables it reads. When a write goes through drift (insert, update, delete, batch, or a custom statement that declares its tables), drift reports which tables changed. Every active stream that reads one of those tables runs its query again and emits the new result.
Because the diagram fence must follow the required format, here it is in full:
Three consequences follow from this design.
- Granularity is the table, not the row. Inserting a finished to-do triggers a re-run of
watchOpenItems()even though the new row does not match itswhereclause. The query runs again and may produce an identical list. Keep stream queries cheap, and usewhereandlimitso that a re-run reads little. - Streams are lazy. Nothing runs until someone listens. Creating the stream costs almost nothing, and the first result arrives asynchronously after
listen. - Transactions notify once. Writes inside a transaction are announced after it commits, so listeners never see a half-finished state. The transactions chapter covers this in more detail.
Watching a single row or a value
Use watchSingle() and watchSingleOrNull() when the result is one row. A common case is a detail screen that must react if the row is edited or deleted.
// Inside AppDatabase
Stream<TodoItem?> watchItem(int id) {
return (select(todoItems)..where((t) => t.id.equals(id)))
.watchSingleOrNull();
}Use watchSingleOrNull() here. With watchSingle(), deleting the row makes the stream emit an error, because the query no longer returns exactly one row.
Aggregates use selectOnly and map. Selecting only the count avoids loading whole rows just to call .length on them.
// Inside AppDatabase
Stream<int> watchOpenCount() {
final count = todoItems.id.count();
final query = selectOnly(todoItems)
..addColumns([count])
..where(todoItems.isDone.equals(false));
return query.map((row) => row.read(count)!).watchSingle();
}Using the stream in a widget
The earlier snippet built the stream inside StreamBuilder. That works, but a more careful version avoids two problems. First, a stream created inside build is recreated on every rebuild, so StreamBuilder resubscribes and briefly shows a waiting state. Second, the snippet ignored errors and the loading state. Create the stream once in the State object and handle every connection state:
import 'package:flutter/material.dart';
import 'database.dart';
class OpenItemsList extends StatefulWidget {
const OpenItemsList({super.key, required this.db});
final AppDatabase db;
@override
State<OpenItemsList> createState() => _OpenItemsListState();
}
class _OpenItemsListState extends State<OpenItemsList> {
late final Stream<List<TodoItem>> _items = widget.db.watchOpenItems();
@override
Widget build(BuildContext context) {
return StreamBuilder<List<TodoItem>>(
stream: _items,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Could not load items: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final items = snapshot.data!;
if (items.isEmpty) {
return const Center(child: Text('Nothing to do'));
}
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) =>
ListTile(title: Text(items[index].title)),
);
},
);
}
}The widget never calls a refresh method. A button elsewhere in the app can call db.addItem('Buy milk'), and the list updates because the write notifies the stream.
If your widget needs different filters over time, such as a search box, create a new stream when the filter changes. Do it in setState or didUpdateWidget, not in build.
Transforming and combining streams
A drift stream is an ordinary Dart Stream, so map, where, and asyncMap work on it. Do light shaping in Dart, for example turning rows into view models:
// Inside AppDatabase
Stream<List<String>> watchOpenTitles() {
return watchOpenItems().map(
(items) => [for (final item in items) item.title],
);
}Keep the filtering that decides which rows load in SQL, where it is cheaper. Filter in Dart only for shaping what you already have.
Writes that drift cannot see
Drift can only notify listeners about changes it knows about. Two situations hide changes from it:
- Raw SQL.
customStatementdoes not say which tables it touches. ForcustomUpdateandcustomInsert, passupdates: {todoItems}so drift can notify. After acustomStatement, callmarkTablesUpdated({todoItems}). - Another connection. If a second database object opens the same file, each object tracks its own changes. Share a single
AppDatabaseinstance across the app. Multiple connections are an advanced setup that needs extra configuration.
A symptom of either problem is a UI that updates only after a restart. The data is saved, but no stream was told to re-run.
Common mistakes
- Building the stream in
build. This causes flicker and repeated resubscription. Create it once ininitStateor alate finalfield. - Using
watchSingle()for a row that can vanish. UsewatchSingleOrNull(). - Watching a large unfiltered table. Every write re-reads every matching row. Add
whereandlimit. - Expecting an emission only for visible changes. A stream may re-emit a list that looks the same. Do not run side effects, such as navigation or snackbars, from a stream listener on the assumption that each event means a real change.
- Forgetting that the first event is the current state. A stream listener runs once for existing data, not only for later changes.
Exercise
A detail screen shows one to-do with watchSingle(). The user deletes that to-do from another screen, and the detail screen shows an error. What change fixes this, and what should the screen display afterwards?
Show answer
Replace watchSingle() with watchSingleOrNull() so the stream emits null when the row is gone instead of raising an error. In the builder, treat a null value as "item no longer exists", for example by showing a message or popping the screen.
Exercise
You run await customStatement('UPDATE todo_items SET is_done = 1') and a screen using watchOpenItems() does not change. Why, and how do you fix it?
Show answer
customStatement does not tell drift which tables it modified, so no stream is notified. Call markTablesUpdated({todoItems}) after the statement. Alternatively, use customUpdate with updates: {todoItems}, or write the change with the typed update(todoItems) API.