What is the primary advantage of Drift over raw sqflite queries?
Drift translates Dart table definitions into SQLite tables with full compile-time type safety and reactive stream queries.
Build offline-first apps using Drift with reactive streams, type safety, migrations, and transactions
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
When building production Flutter applications, relying on key-value storage (SharedPreferences) is insufficient for structured relational data. Raw SQLite (sqflite) works, but writing raw SQL query strings introduces typing errors, runtime typos, and zero reactive UI updates.
Drift (formerly Moor) is the premier persistence library for Flutter and Dart. It provides:
watch()): When your database changes, your UI automatically updates without manual reload code.With Drift, you define database tables as clean Dart classes. Drift's code generator creates the companion classes, queries, and serializers automatically.
1import 'package:drift/drift.dart';23// 1. Define the Todos Table4class Todos extends Table {5IntColumn get id => integer().autoIncrement()();6TextColumn get title => text().withLength(min: 1, max: 100)();7TextColumn get content => text().named('body')();8BoolColumn get isCompleted => boolean().withDefault(const Constant(false))();9DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();10}1112// 2. Define the Database class13@DriftDatabase(tables: [Todos])14class AppDatabase extends _\$AppDatabase {15AppDatabase(QueryExecutor e) : super(e);1617@override18int get schemaVersion => 1;1920// Type-safe CRUD operations:21Future<List<Todo>> getAllTodos() => select(todos).get();22Future<int> insertTodo(TodosCompanion entry) => into(todos).insert(entry);23Future<bool> updateTodo(Todo entry) => update(todos).replace(entry);24Future<int> deleteTodo(int id) => (delete(todos)..where((t) => t.id.equals(id))).go();25}
watch())The most transformative feature of Drift is the watch() query method.
Instead of returning a single Future, watch() returns a continuous Stream. Whenever any part of your app inserts, updates, or deletes a row in that table, Drift automatically queries the updated result and emits it down the stream!
// In your Repository or Database:
Stream<List<Todo>> watchAllTodos() {
return (select(todos)..orderBy([(t) => OrderingTerm.desc(t.createdAt)])).watch();
}
// In your Flutter UI:
StreamBuilder<List<Todo>>(
stream: database.watchAllTodos(),
builder: (context, snapshot) {
final todos = snapshot.data ?? [];
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) => ListTile(
title: Text(todos[index].title),
trailing: Checkbox(
value: todos[index].isCompleted,
onChanged: (val) => database.updateTodo(
todos[index].copyWith(isCompleted: val ?? false),
),
),
),
);
},
);
Because watch() updates automatically, your UI can observe the local Drift stream as the Single Source of Truth. When background network sync writes to Drift, your UI reflects the fresh data instantly with zero manual refresh logic!
When you release app updates that add new columns or tables, Drift's MigrationStrategy lets you modify tables safely:
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) async {
await m.createAll();
},
onUpgrade: (m, from, to) async {
if (from < 2) {
// Version 2 added a priority column:
await m.addColumn(todos, todos.priority);
}
},
);
Whenever you edit Drift table definitions, always regenerate companion classes using: dart run build_runner build --delete-conflicting-outputs.
Build offline first apps using Drift with reactive streams, type safety, migrations, and transactions. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.
Think in architecture, reliability, and team-level maintainability.
Prefer readable names, explicit intent, and async/await over deeply nested callbacks.
When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.
Strong Dart habits lead to predictable APIs and cleaner boundaries between presentation and business logic.
As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.
Drift translates Dart table definitions into SQLite tables with full compile-time type safety and reactive stream queries.
.watch() creates a reactive stream that fires whenever matching database rows are inserted, updated, or deleted.
Drift uses schemaVersion and MigrationStrategy to execute versioned ALTER TABLE and CREATE TABLE commands without data loss.
Drift uses Dart's build_runner to generate type-safe database companions and query parsers.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue