Sub topic 9
Watching Queries as Streams
This chapter assumes you know Dart async and await, Flutter widgets, and StreamBuilder. It also assumes that AppDatabase and the TodoItems table from earlier chapters already exist.
A drift query can be watched instead of read once. A watched query returns a Dart Stream, which emits a new result whenever drift detects a relevant database change. This lets the database drive the UI without manually calling setState after every insert or update.
How a watched query works
A one-time query uses get():
final items = await db.select(db.todoItems).get();The returned list represents the database at that moment. A watched query uses watch():
final itemsStream = db.select(db.todoItems).watch();The stream usually emits an initial result and then emits again when the query result may have changed. Drift tracks table dependencies, so an update to an unrelated table does not normally refresh this query.
Filtering the stream before showing it
Put filtering, ordering, and limits in the drift query. This keeps unnecessary rows out of memory and makes the database perform the work.
Stream<List<TodoItem>> watchOpenItems(AppDatabase db) {
return (db.select(db.todoItems)
..where((todo) => todo.isDone.equals(false))
..orderBy([
(todo) => OrderingTerm.desc(todo.createdAt),
]))
.watch();
}The query watches todoItems, filters out completed rows, and places the newest open item first.
Connecting a stream to Flutter
StreamBuilder subscribes to a stream and rebuilds its builder whenever the stream emits. Handle the loading and error states rather than assuming that snapshot.data is always available.
import 'package:flutter/material.dart';
class TodoList extends StatelessWidget {
const TodoList({
required this.database,
super.key,
});
final AppDatabase database;
@override
Widget build(BuildContext context) {
return StreamBuilder<List<TodoItem>>(
stream: watchOpenItems(database),
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('No open items'));
}
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text(items[index].title));
},
);
},
);
}
}The stream should normally be stable while the widget is mounted. Creating a new stream object during every build can cause needless subscriptions. For simple drift queries, storing the stream in a State object or exposing a stable database method is safer when rebuilds are frequent.
Common errors
- Watching all rows when the screen needs only a filtered subset.
- Ignoring
snapshot.hasError, which hides database failures. - Recreating subscriptions unnecessarily in
build. - Forgetting to close the database when the application or test no longer needs it.
Exercise
Why does watchOpenItems update the list after an item changes from incomplete to complete?
Show answer
The query depends on todoItems. Drift notices the table change, reruns the filtered query, and emits a new list without that completed item.