Learn/Local Storage/Drift: Reactive Type-Safe SQLite Database

Drift: Reactive Type-Safe SQLite Database

Build offline-first apps using Drift with reactive streams, type safety, migrations, and transactions

15 min~6 min read+55 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. 1. Defining Tables in Pure Dart
  2. 2. 2. The Power of Reactive Queries (`watch()`)
  3. 3. 3. Schema Migrations Without Data Loss
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Quick Glossary
  11. 11. Architecture Lens

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

Drift: Reactive Type-Safe SQLite Database

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:

  1. 100% Type-Safe Queries: Write table definitions and queries in pure Dart.
  2. Auto-Updating Reactive Streams (watch()): When your database changes, your UI automatically updates without manual reload code.
  3. Robust Migrations: Type-safe database upgrades across app releases.
  4. Cross-Platform: Works seamlessly across iOS, Android, macOS, Windows, Linux, and Web.

1. Defining Tables in Pure Dart

With Drift, you define database tables as clean Dart classes. Drift's code generator creates the companion classes, queries, and serializers automatically.

dart
1import 'package:drift/drift.dart';
2
3// 1. Define the Todos Table
4class Todos extends Table {
5 IntColumn get id => integer().autoIncrement()();
6 TextColumn get title => text().withLength(min: 1, max: 100)();
7 TextColumn get content => text().named('body')();
8 BoolColumn get isCompleted => boolean().withDefault(const Constant(false))();
9 DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
10}
11
12// 2. Define the Database class
13@DriftDatabase(tables: [Todos])
14class AppDatabase extends _\$AppDatabase {
15 AppDatabase(QueryExecutor e) : super(e);
16
17 @override
18 int get schemaVersion => 1;
19
20 // Type-safe CRUD operations:
21 Future<List<Todo>> getAllTodos() => select(todos).get();
22 Future<int> insertTodo(TodosCompanion entry) => into(todos).insert(entry);
23 Future<bool> updateTodo(Todo entry) => update(todos).replace(entry);
24 Future<int> deleteTodo(int id) => (delete(todos)..where((t) => t.id.equals(id))).go();
25}

2. The Power of Reactive Queries (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),
          ),
        ),
      ),
    );
  },
);

Offline-First UI Sync

💡 Offline-First UI Sync

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!

3. Schema Migrations Without Data Loss

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);
    }
  },
);

Run build_runner After Schema Edits

⚠️ Run build_runner After Schema Edits

Whenever you edit Drift table definitions, always regenerate companion classes using: dart run build_runner build --delete-conflicting-outputs.

Drift Database Best Practices

  • Define tables in pure Dart to get compile-time type safety on all columns.
  • Use select().watch() to bind your Flutter UI directly to reactive database streams.
  • Keep your Database instance as a singleton or scoped provider via Riverpod/GetIt.
  • Increment schemaVersion and write explicit migration steps inside onUpgrade when adding columns.
  • Use transactions (transaction(() async { ... })) when performing multiple related writes.

This Lesson In Simple Words

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.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What is the primary advantage of Drift over raw sqflite queries?".

Quick Glossary

  • build: The method that describes UI for the current state.
  • stream: A sequence of asynchronous values over time.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

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.

Lesson Completion Checklist

  • I can explain "Drift: Reactive Type-Safe SQLite Database" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

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.

What does calling .watch() on a Drift query return?

.watch() creates a reactive stream that fires whenever matching database rows are inserted, updated, or deleted.

How do you handle schema changes (like adding a column) between app releases in Drift?

Drift uses schemaVersion and MigrationStrategy to execute versioned ALTER TABLE and CREATE TABLE commands without data loss.

Which CLI command generates the required Drift database companion code?

Drift uses Dart's build_runner to generate type-safe database companions and query parsers.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

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