Sub topic 1
SQLite on Device and Where Drift Fits
This chapter explains what SQLite is, why it suits on-device storage in Flutter, and what drift adds on top of it. It sets up the decisions behind the rest of the tutorial. You won't write a full app here.
Prerequisites
This chapter assumes you already have:
- Basic Dart and Flutter knowledge: widgets,
StatefulWidget, andStreamBuilder. - Comfort with
async/await,Future, andStreamin Dart. - A working idea of relational databases: tables, rows, columns, and primary keys.
- The ability to run commands with the
dartandflutterCLI.
You don't need to know SQL in depth. The few statements used here are explained as they appear.
What SQLite is, and why it lives on the device
SQLite is a relational database engine that runs inside your app's process. There is no server and no network connection. The whole database is one file on the device's storage, and the engine is a C library that reads and writes that file directly.
This has several practical consequences:
- Reads and writes are local. A query takes microseconds to milliseconds, and the app works offline.
- You get real database features. SQLite supports indexes, constraints, joins, transactions, and ACID guarantees. A crash in the middle of a write does not leave half-written data.
- It is private to your app. On Android and iOS the file sits in the app's sandbox, so other apps cannot read it.
- It is the same engine on every platform. Android and iOS ship with it, and Flutter packages can bundle it for desktop and the web.
Here is a small piece of SQL for the to-do data used throughout this tutorial:
CREATE TABLE todo_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
is_done INTEGER NOT NULL DEFAULT 0
);
INSERT INTO todo_items (title) VALUES ('Write tests');
SELECT id, title FROM todo_items WHERE is_done = 0 ORDER BY id DESC;SQLite has no separate boolean type, so is_done is stored as the integer 0 or 1. A library that maps this to a Dart bool has to know about that detail.
When a database is the right tool
A database is not always needed. Choose by the shape of your data and the questions you ask of it.
| Option | Good for | Breaks down when |
|---|---|---|
| `shared_preferences` | A few settings, flags, small values | You need lists of records or queries |
| JSON file | A small document that you read and write whole | The file grows, or you need to change one record often |
| `sqflite` | SQLite with raw SQL strings and maps | You want compile-time checks or change notifications |
| `drift` | Structured, queryable, evolving data with a reactive UI | The data is a handful of settings, where it is overkill |
A good signal for a database is that you say things like "show all unfinished items, newest first" or "find the orders for this customer". Those are queries, and a database answers them without loading everything into memory.
The cost of raw SQL in Dart
The sqflite package exposes SQLite directly. Each query is a string, and each result row is a Map<String, Object?>:
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<void> rawExample() async {
final path = join(await getDatabasesPath(), 'raw_example.db');
final db = await openDatabase(
path,
version: 1,
onCreate: (db, version) => db.execute(
'CREATE TABLE todo_items ('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'is_done INTEGER NOT NULL DEFAULT 0)',
),
);
await db.insert('todo_items', {'title': 'Write tests'});
final rows = await db.query(
'todo_items',
where: 'is_done = ?',
whereArgs: [0],
);
// A typo in a key compiles fine and returns null at runtime.
final title = rows.first['titel'];
print(title); // null
}Nothing in this code is wrong to the compiler, yet it has several weaknesses:
- Column names and SQL are plain strings, so typos surface at runtime.
- Values come back as
Object?and you cast them yourself. is_doneis anint, and converting it to aboolis your job.- Changing the schema means editing SQL strings in several places.
- To refresh a screen after a write, you call the query again by hand.
None of these is fatal in a small app. They accumulate as the schema grows and several screens read the same tables.
Where drift fits
drift is a Dart persistence library built on SQLite. It keeps the engine and replaces the string handling. You describe the schema as Dart classes, and a code generator produces the typed pieces.
This is what a table definition looks like in drift. The next chapters cover it in detail.
import 'package:drift/drift.dart';
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
}From this one class, drift gives you:
- Typed rows. A generated
TodoItemclass hasString titleandbool isDonefields. Thetiteltypo from the raw example becomes a compile error. - Typed queries. You write
select(todoItems)..where((t) => t.isDone.equals(false)). The column references are Dart members, so autocomplete and refactoring work. - Reactive queries. Calling
.watch()instead of.get()returns aStreamthat emits a new result when the underlying tables change. This is what drives aStreamBuilder. - Schema support. drift tracks a schema version and gives you hooks for migrations, so existing users keep their data when the schema changes.
- Testable connections. The database takes a
QueryExecutor, so tests can use an in-memory database.
The raw SQL is still available when you need it. drift does not hide SQLite, and you can run custom statements and use SQLite-specific features.
How the pieces connect
The workflow has a build step. Your table classes are the source of truth, build_runner turns them into generated Dart, and your database class uses that output at runtime to talk to SQLite.
Two points about the internals matter for later chapters:
- Generation happens at build time, not at runtime. The generated
.g.dartfile is ordinary Dart that you commit or regenerate. If you change a table and forget to rerun the generator, your code and the generated code disagree, and the compiler reports it. - Stream updates come from drift itself. drift watches the writes that go through its own API and re-runs affected queries. A write made by a separate connection outside drift will not wake the stream.
Trade-offs and common errors
drift has costs, and you should know them before adopting it.
- A build step. You need
build_runner, and generated files add to build time. Large schemas make generation slower. - A learning curve. The query builder has its own vocabulary, such as companions,
OrderingTerm, andjoin. The following chapters cover them. - Migrations are your responsibility. Changing a table without raising
schemaVersionand writing a migration will break installed apps. Chapter 12 of this tutorial's plan covers this. - Overkill for tiny data. For three settings,
shared_preferencesis simpler.
Errors that new users commonly hit:
- Forgetting the
part 'database.g.dart';line, which leaves_$AppDatabaseundefined. - Editing a table and not rerunning
dart run build_runner build. - Treating a stream as free. A
watch()that you recreate on everybuildcall opens a new subscription each time. Create the stream once and reuse it. - Assuming the database file is shared across apps. It is private to the app that created it.
What you will build next
The following chapters follow the concept graph for this tutorial: install drift, define tables, run the generator, create the database class, then insert, read, update, and delete rows. After that come reactive streams, transactions, migrations, joins, and tests. Each chapter uses the same to-do example so the pieces fit together.
Exercise
You are building a Flutter app that stores a user's theme choice (light or dark) and a list of thousands of notes that the user searches by keyword and sorts by date. Which storage would you pick for each, and why?
Show answer
Use shared_preferences for the theme choice, because it is one small value with no queries. Use SQLite through drift for the notes, because you need filtering, sorting, and indexes over many records, and a reactive stream keeps the list on screen current after edits. Loading thousands of notes from a JSON file into memory to search them would be slow and wasteful.
Exercise
A teammate edits a drift table class to add a column, but the app still fails to compile with errors about the row class. What step did they most likely skip, and what is a second step they will need before shipping to existing users?
Show answer
They skipped rerunning the code generator (dart run build_runner build), so the generated row class does not match the table. Before shipping, they must raise schemaVersion and add a migration step, so existing installs gain the new column without losing data.