Sub topic 10
Showing live data with StreamBuilder
This chapter assumes you know basic Dart async and await, Flutter widgets, and the StreamBuilder widget. It also assumes that AppDatabase and TodoItem were defined in the previous chapters.
A drift query becomes reactive when you call watch() instead of get(). A get() call returns one Future containing one result. A watch() call returns a Stream, which emits a new result when drift detects a relevant database change.
Create a query stream
Suppose AppDatabase has this method:
Stream<List<TodoItem>> watchOpenItems() {
return (select(todoItems)
..where((t) => t.isDone.equals(false))
..orderBy([(t) => OrderingTerm.desc(t.createdAt)]))
.watch();
}The query emits only unfinished items, ordered with the newest item first. Drift runs the query initially and then runs it again when a change might affect the result.
The stream does not save data. An insert, update, or delete causes the stream to emit. The widget listens to those emissions.
Connect the stream to a widget
Create the stream once in initState. This keeps the same stream subscription while the widget rebuilds for other reasons.
import 'package:flutter/material.dart';
class OpenItemsPage extends StatefulWidget {
const OpenItemsPage({
super.key,
required this.db,
});
final AppDatabase db;
@override
State<OpenItemsPage> createState() => _OpenItemsPageState();
}
class _OpenItemsPageState extends State<OpenItemsPage> {
late final Stream<List<TodoItem>> _items;
@override
void initState() {
super.initState();
_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.requireData;
if (items.isEmpty) {
return const Center(
child: Text('No open items'),
);
}
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
title: Text(item.title),
);
},
);
},
);
}
}StreamBuilder supplies an AsyncSnapshot to the builder. The snapshot contains the latest data, an error if the stream failed, and the connection state.
Handle the states in this order:
- Check
hasErrorand show an error message. - Check
hasDataand show a loading indicator until the first result arrives. - Read the list and show either its contents or an empty-state message.
Avoid common stream errors
Do not create a new database or a new stream subscription inside build. Flutter can call build many times. Creating resources there can cause repeated subscriptions and wasted work.
Also, close the database at the ownership boundary that created it. A page that only receives AppDatabase should not close it when the page is disposed. The application or repository that opened the database owns its lifetime.
Exercise
Why should a watched stream usually be created in initState instead of directly in build?
Show answer
build can run many times, so creating the stream in build can replace the subscription repeatedly. Creating it in initState keeps one stream for the widget's lifetime.