Sub topic 3
Showing live data with StreamBuilder
This chapter assumes you know Dart, Flutter widgets (including StatefulWidget), async/await, and Streams. You should also have the TodoItems table and AppDatabase class from the earlier chapters.
Watching a query
A query ending in .watch() returns a Stream. The stream emits a new list whenever the table changes. StreamBuilder rebuilds the widget on each emission.
Stream<List<TodoItem>> watchOpenItems() {
return (select(todoItems)
..where((t) => t.isDone.equals(false)))
.watch();
}
StreamBuilder<List<TodoItem>>(
stream: db.watchOpenItems(),
builder: (context, snapshot) {
final items = snapshot.data ?? const [];
return ListView(
children: [for (final item in items) ListTile(title: Text(item.title))],
);
},
)Common errors:
- Calling
allItems()inbuild()instead ofwatch. The list never updates. - Forgetting that
snapshot.datais null before the first emission.
Keeping related writes together with transactions
A transaction groups several writes. If one fails, drift rolls back all of them.
import 'package:drift/drift.dart';
Future<void> completeAll(List<int> ids) => transaction(() async {
for (final id in ids) {
await (update(todoItems)..where((t) => t.id.equals(id)))
.write(const TodoItemsCompanion(isDone: Value(true)));
}
});Evolving the schema with migrations
Increase schemaVersion when the table changes. Use onUpgrade to alter existing installs without losing data.
@override
int get schemaVersion => 2;
@override
MigrationStrategy get migration => MigrationStrategy(
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.addColumn(todoItems, todoItems.note);
}
},
);Combining tables with joins
A join pairs rows from two tables. Use leftOuterJoin when a to-do may have no category.
Storing custom types with converters
A TypeConverter maps a Dart type to a column type. This example stores an enum as an integer.
enum Priority { low, high }
class PriorityConverter extends TypeConverter<Priority, int> {
const PriorityConverter();
@override
Priority fromSql(int fromDb) => Priority.values[fromDb];
@override
int toSql(Priority value) => value.index;
}
// In TodoItems:
// IntColumn get priority => integer().map(const PriorityConverter())();Structuring larger apps with DAOs
A DAO (data access object) is a class that groups queries for one area of the app. Annotate it with @DriftAccessor and list its tables.
Testing queries against an in-memory database
Pass NativeDatabase.memory() to the database. Each test gets a fresh database with no files on disk.
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() async => db.close());
test('inserted items can be read back', () async {
await db.addItem('Write tests');
final items = await db.allItems();
expect(items.single.title, 'Write tests');
});
}Moving database work off the main isolate
Long queries can freeze the UI when they run on the main isolate. Use NativeDatabase.createInBackground(file) to run SQLite on a background isolate.
Exercise
Exercise
Why does watchOpenItems() update the UI after an insert, while allItems() called in build() does not?
Show answer
watch() returns a stream that emits a new list whenever the table changes, so StreamBuilder rebuilds. allItems() returns one snapshot of the table at the time it runs, and nothing triggers a rebuild when the data changes later.