Sub topic 10
Showing live data with StreamBuilder
The previous chapters covered watch(), which turns a query into a stream that emits a new list whenever the underlying tables change. This chapter connects that stream to the widget tree with StreamBuilder. It also covers the mistakes that cause wasted queries or confusing screens.
This chapter assumes you can read a StreamBuilder snapshot, that AppDatabase and watchOpenItems() exist as built earlier, and that you know the lifecycle of a StatefulWidget.
What the stream gives you
A drift watch stream behaves in a predictable way:
- When someone listens, drift runs the query and emits the first result.
- After that, it re-runs the query and emits again whenever a write touches a table the query reads.
- Writes from anywhere in your app trigger the update, whether they come from a button, a background sync, or a different screen.
- A query that reads no changed table is not re-run.
So the UI never asks "should I refresh?" The UI only writes to the database and the stream delivers the new state.
A complete screen
This example assumes database.dart holds the AppDatabase from earlier chapters, including watchOpenItems(), addItem() and updateItem().
import 'package:flutter/material.dart';
import 'database.dart';
void main() {
runApp(TodoApp(db: AppDatabase()));
}
class TodoApp extends StatelessWidget {
const TodoApp({super.key, required this.db});
final AppDatabase db;
@override
Widget build(BuildContext context) =>
MaterialApp(home: TodoPage(db: db));
}
class TodoPage extends StatefulWidget {
const TodoPage({super.key, required this.db});
final AppDatabase db;
@override
State<TodoPage> createState() => _TodoPageState();
}
class _TodoPageState extends State<TodoPage> {
late Stream<List<TodoItem>> _items;
@override
void initState() {
super.initState();
_items = widget.db.watchOpenItems();
}
@override
void didUpdateWidget(TodoPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.db != widget.db) {
_items = widget.db.watchOpenItems();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('To-do')),
body: StreamBuilder<List<TodoItem>>(
stream: _items,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Could not load: ${snapshot.error}'));
}
final items = snapshot.data;
if (items == null) {
return const Center(child: CircularProgressIndicator());
}
if (items.isEmpty) {
return const Center(child: Text('Nothing to do'));
}
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return CheckboxListTile(
key: ValueKey(item.id),
value: item.isDone,
title: Text(item.title),
onChanged: (_) => widget.db
.updateItem(item.copyWith(isDone: !item.isDone)),
);
},
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => widget.db.addItem('Task ${DateTime.now()}'),
child: const Icon(Icons.add),
),
);
}
}Tapping a checkbox marks the item done. The watched query only selects open items, so the row disappears from the list without any setState call. The floating button inserts a row and it appears at the top, because the query orders by createdAt descending.
Reading the snapshot correctly
The builder runs many times, so it must handle each state the snapshot can be in. The order of the checks matters.
| Snapshot condition | Meaning | What to show |
|---|---|---|
| `hasError` | The query or the connection failed | An error message |
| `data == null` | No result has arrived yet | A progress indicator |
| `data` is empty | The query ran and matched nothing | An empty-state message |
| `data` is non-empty | Normal case | The list |
Check data == null rather than connectionState == ConnectionState.waiting. If the stream is replaced, the snapshot can report waiting while still holding the previous data, and you usually want to keep showing that data. Treating "no rows" and "not loaded yet" as the same state is a common error. It makes an empty list flash a spinner, or a spinner look like an empty list.
Where to create the stream
A watch stream should be created once and reused. Putting the call inside build looks like this:
// Avoid: a new stream object on every rebuild
StreamBuilder<List<TodoItem>>(
stream: widget.db.watchOpenItems(),
builder: (context, snapshot) { /* ... */ },
)StreamBuilder compares the stream it receives with the previous one. A new object means it cancels the old subscription, subscribes again, and drift runs the query again. Any rebuild of the parent, such as a keyboard opening or a theme change, repeats this for no reason.
Create the stream in initState, as in the example. Recreate it only when its inputs change. A search screen is the typical case. When the search text changes, build a new stream with a new where clause and assign it inside setState.
void _onSearchChanged(String text) {
setState(() {
_items = widget.db.watchMatching(text);
});
}Here watchMatching is a method you would add to AppDatabase, using where((t) => t.title.like('%$text%')).
Ownership of the database
The widget in the example receives the database through its constructor. That is enough for one screen. In a larger app, make one AppDatabase instance and share it through whatever you already use for dependency injection, such as InheritedWidget, Provider, or Riverpod.
Two rules apply:
- Open one database per file. Two
AppDatabaseobjects pointing at the same file do not see each other's writes as stream events, so their watch streams can go stale. Drift warns about this in debug builds. - Close the database in the place that created it, usually in the
disposeof a rootStateobject. A screen that merely receives the database must not close it.
What drift emits, and what it does not
Drift re-runs a watched query when a write touches one of its tables. It does not check whether the write changed the rows that your query returns. Updating a done item still re-runs watchOpenItems(), even though the open list is the same.
The emitted list can therefore equal the previous one. That is harmless for a ListView, because Flutter compares widgets and keeps the work small. If the stream feeds something costly, add .distinct() with a list equality check.
import 'package:flutter/foundation.dart';
Stream<List<TodoItem>> watchOpenItemsDistinct() =>
watchOpenItems().distinct(listEquals);The generated data classes implement == by value, so listEquals works on them.
Rapid writes are also grouped. If many writes happen in a row, such as inserting 500 rows in a loop, the watcher may emit several times. Wrapping the writes in a transaction, covered in a later chapter, gives one notification when it finishes.
Handling errors and slow starts
The first emission needs the database to open. On first launch that includes creating the file and running onCreate, so the spinner can show for a noticeable moment. Errors in the SQL surface as stream errors, which is why the builder checks hasError first. Without that check, a failed query leaves you with a spinner that never ends, because data stays null.
Common mistakes
- Calling
setStateafter a write to "refresh" the list. The stream already does it, and the extra call hides the real data flow. - Using
FutureBuilderwithallItems()for data that changes. It shows a snapshot of one moment and goes stale. - Missing keys on list items. Without
ValueKey(item.id), Flutter matches rows by position, so checkbox animations can attach to the wrong row when items are removed. - Filtering in Dart after
watch(). Put the filter in thewhereclause so SQLite does the work and the stream skips irrelevant updates.
Exercise
A teammate wrote stream: widget.db.watchOpenItems() directly inside build. The list displays correctly. Give two reasons to move it to initState, and say when you would recreate the stream anyway.
Show answer
Every rebuild of the widget creates a new stream object, so StreamBuilder cancels its subscription and subscribes again, and drift re-runs the query each time. That is wasted database work, and the snapshot restarts its connection state on each change. Moving the call to initState creates one stream that lives as long as the State. Recreate the stream, inside setState, only when the query's inputs change, for example the search text or a selected category.
Exercise
Your screen shows "Nothing to do" for a split second on launch, then the real list appears. Which snapshot check is missing, and what is the fix?
Show answer
The builder treats a null data the same as an empty list, or it checks items.isEmpty before it checks data == null. Check snapshot.data == null first and show a progress indicator. Then check items.isEmpty and show the empty-state message. Check hasError before both.