Skip to main content

Mobile development · Intermediate · 32 min

Store data in a Flutter app with Drift and SQLite

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14.0 · drift 2.35.4

You will build a small shop credit book in Flutter 3.50 that keeps customers and what they owe in SQLite through Drift 2.35, with typed queries, a join, a list that redraws itself from a watch() stream, a tested schema migration and in-memory tests for all of it.

On this page

Most apps need to remember more than a few settings. Once you have lists of records that relate to each other, filter them, add them up and change their shape between releases, you want a real database. On a phone that database is almost always SQLite, and in Flutter the most complete way to use it is Drift: you describe tables as Dart classes, a code generator writes typed row classes and query helpers, and any query can become a stream that pushes new results to the screen whenever the data changes.

In this tutorial you build a credit book for a small shop. Many shopkeepers let regular customers buy now and pay at the end of the week, and keep a paper book of who owes what. Your app keeps that book on the phone: customers, each item they took, and a running total per customer. It works with no network at all, which suits people on prepaid data or patchy coverage, and costs them nothing to open.

You write the tables, a data access object with a join, a screen that redraws itself from a watch() stream, then change the schema in a second release and prove the migration keeps existing data. Everything is checked with flutter analyze and flutter test on your computer, against an in-memory database, with no device needed.

Step 1 · Create the project and add Drift

Check the SDK first:

Bash
flutter --version

The first line should start with Flutter 3.50.1 (or a later 3.50 release) and the Dart line should say 3.14.

Create a phone-only project in a practice folder, remove the starter counter test, and add Drift. drift is the runtime library, drift_flutter opens a database file in the right place on each platform, and path_provider supplies that place. drift_dev and build_runner are development tools that generate code; they are never shipped in the app:

Bash
mkdir -p ~/flutter-drift-demo
cd ~/flutter-drift-demo
flutter create --platforms=android,ios tab_book
cd tab_book
rm test/widget_test.dart
flutter pub add drift:^2.35.4 drift_flutter:^0.3.1 path_provider:^2.1.6 dev:drift_dev:^2.35.3 dev:build_runner:^2.17.1

Drift talks to SQLite through the sqlite3 package, which arrives as a dependency of drift. Since version 3, sqlite3 bundles its own copy of SQLite with your app instead of using whatever the phone's operating system ships, so every user gets the same SQLite version and features. The first build or test run downloads that prebuilt library once and checks it against a hash, so do it on Wi-Fi if your data is metered.

Flutter 3.50 moved the Material widgets into their own package, material_ui, and flutter create already lists it in pubspec.yaml. The screens and widget tests in this tutorial import package:material_ui/material_ui.dart. The older package:flutter/material.dart still works but is deprecated, so flutter analyze would report it.

Generated files will live next to your own code. Tell the analyser not to report on them, and keep the Flutter lint rules for everything else, by replacing analysis_options.yaml:

Bash
cd ~/flutter-drift-demo/tab_book
cat > analysis_options.yaml <<'YAML'
include: package:flutter_lints/flutter.yaml

analyzer:
  exclude:
    - "**/*.g.dart"
    - lib/data/schema_versions.dart
    - test/generated_migrations/**
YAML

Check it worked

Bash
cd ~/flutter-drift-demo/tab_book
grep -E '^  (drift|drift_flutter|path_provider|material_ui|drift_dev|build_runner):' pubspec.yaml
flutter analyze

grep prints six lines, one per package with its version range (material_ui came from flutter create), and flutter analyze ends with No issues found!.

Step 2 · Describe the tables as Dart classes

A Drift table is a class that extends Table. Each getter is a column: the builder chain says its type and constraints, and the empty () at the end closes the definition. Put the tables in their own file:

Bash
cd ~/flutter-drift-demo/tab_book
mkdir -p lib/data
cat > lib/data/tables.dart <<'DART'
import 'package:drift/drift.dart';

class Customers extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text().withLength(min: 1, max: 80)();
  TextColumn get phone => text().nullable()();
}

class TabEntries extends Table {
  IntColumn get id => integer().autoIncrement()();
  IntColumn get customerId => integer().references(Customers, #id)();
  TextColumn get item => text().withLength(min: 1, max: 120)();
  IntColumn get amountCents => integer()();
  DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
}
DART

A few choices here are worth copying in your own apps:

  • Money is stored as a whole number of the smallest unit (cents, kobo, shillings' cents). A double cannot hold 0.10 exactly, and the errors add up over a week of small sales.
  • customerId references Customers, so SQLite can refuse an entry for a customer who does not exist. That check is only enforced once foreign keys are switched on, which the database class does next.
  • Column and table names in SQL are the snake_case form of the getters: tab_entries, customer_id, amount_cents.

The database class lists the tables and says which version of the schema the code expects. Keep it free of Flutter imports: Drift's command-line tools load this file later with plain Dart, and plain Dart cannot load Flutter. The connection is passed in from outside, so the app can give it a file on the phone and the tests an in-memory database:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/database.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/tables.dart';

part 'database.g.dart';

@DriftDatabase(tables: [Customers, TabEntries])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.e);

  @override
  int get schemaVersion => 1;

  @override
  MigrationStrategy get migration => MigrationStrategy(
    beforeOpen: (details) async {
      await customStatement('PRAGMA foreign_keys = ON');
    },
  );
}
DART
dart run build_runner build

build_runner reads the annotations and writes lib/data/database.g.dart. The first run takes a minute while it compiles the generator. The generated file holds a row class for each table (Customer and TabEntry, singular forms of the table names), a companion class for inserts and updates (CustomersCompanion, TabEntriesCompanion), and the _$AppDatabase base class with a getter per table. Never edit it by hand; run the build again after every change to a table or query annotation. While you work, dart run build_runner watch rebuilds on every save.

Check it worked

Bash
cd ~/flutter-drift-demo/tab_book
ls lib/data
grep -c 'class TabEntry ' lib/data/database.g.dart
flutter analyze

ls shows database.dart, database.g.dart and tables.dart, grep prints 1 because the row class exists, and the analyser finds no issues. If it reports Target of URI hasn't been generated, the build has not run since your last change.

Step 3 · Write typed queries and a join in a DAO

Keep queries out of widgets. A data access object (DAO) is a class that groups the queries for one part of the app, and Drift generates a mixin that gives it the same table getters as the database. This one adds customers and entries, and works out what each customer owes by joining the two tables and adding up the amounts:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/tab_dao.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/database.dart';
import 'package:tab_book/data/tables.dart';

part 'tab_dao.g.dart';

class CustomerBalance {
  const CustomerBalance(this.customer, this.owedCents);

  final Customer customer;
  final int owedCents;
}

@DriftAccessor(tables: [Customers, TabEntries])
class TabDao extends DatabaseAccessor<AppDatabase> with _$TabDaoMixin {
  TabDao(super.attachedDatabase);

  Future<int> addCustomer(String name, {String? phone}) {
    return into(customers).insert(
      CustomersCompanion.insert(name: name, phone: Value(phone)),
    );
  }

  Future<int> addEntry({
    required int customerId,
    required String item,
    required int amountCents,
  }) {
    return into(tabEntries).insert(
      TabEntriesCompanion.insert(
        customerId: customerId,
        item: item,
        amountCents: amountCents,
      ),
    );
  }

  Selectable<CustomerBalance> _balances() {
    final owed = tabEntries.amountCents.sum();
    final query =
        select(customers).join([
            leftOuterJoin(
              tabEntries,
              tabEntries.customerId.equalsExp(customers.id),
              useColumns: false,
            ),
          ])
          ..addColumns([owed])
          ..groupBy([customers.id])
          ..orderBy([OrderingTerm.asc(customers.name)]);
    return query.map(
      (row) => CustomerBalance(row.readTable(customers), row.read(owed) ?? 0),
    );
  }

  Future<List<CustomerBalance>> balances() => _balances().get();

  Stream<List<CustomerBalance>> watchBalances() => _balances().watch();
}
DART

Read _balances as the SQL it produces: select every customer, left-join their entries so customers with no entries still appear, add one extra column holding SUM(amount_cents), group by customer and sort by name. useColumns: false keeps the entry columns out of the result, because only the sum is needed. A customer with no entries has a sum of SQL NULL, which arrives in Dart as null, hence the ?? 0. Everything is typed: customers.name is a text column, so passing it a number is a compile error, not a crash on a customer's phone.

Register the DAO on the database, which makes Drift generate a tabDao getter, and rebuild:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/database.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/tab_dao.dart';
import 'package:tab_book/data/tables.dart';

part 'database.g.dart';

@DriftDatabase(tables: [Customers, TabEntries], daos: [TabDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.e);

  @override
  int get schemaVersion => 1;

  @override
  MigrationStrategy get migration => MigrationStrategy(
    beforeOpen: (details) async {
      await customStatement('PRAGMA foreign_keys = ON');
    },
  );
}
DART
dart run build_runner build

Now test the queries. NativeDatabase.memory() opens a fresh SQLite database in memory, so each test starts empty and nothing touches the disk. Wrapping it in a DatabaseConnection with closeStreamsSynchronously: true makes streams close straight away, which Flutter's test framework needs:

Bash
cd ~/flutter-drift-demo/tab_book
cat > test/tab_dao_test.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tab_book/data/database.dart';

void main() {
  late AppDatabase db;

  setUp(() {
    db = AppDatabase(
      DatabaseConnection(
        NativeDatabase.memory(),
        closeStreamsSynchronously: true,
      ),
    );
  });

  tearDown(() => db.close());

  test('balances join customers to the sum of their entries', () async {
    final amina = await db.tabDao.addCustomer('Amina', phone: '+254700000001');
    await db.tabDao.addCustomer('Tunde');
    await db.tabDao.addEntry(customerId: amina, item: 'Rice 2kg', amountCents: 15000);
    await db.tabDao.addEntry(customerId: amina, item: 'Sugar 1kg', amountCents: 5000);

    final balances = await db.tabDao.balances();

    expect(balances.map((b) => b.customer.name), ['Amina', 'Tunde']);
    expect(balances.map((b) => b.owedCents), [20000, 0]);
    expect(balances.first.customer.phone, '+254700000001');
  });

  test('an entry for a customer who does not exist is refused', () async {
    await expectLater(
      db.tabDao.addEntry(customerId: 99, item: 'Bread', amountCents: 800),
      throwsA(isA<SqliteException>()),
    );
  });
}
DART
flutter test test/tab_dao_test.dart

The second test proves that PRAGMA foreign_keys = ON in beforeOpen is doing its job. beforeOpen runs every time the database opens, before any other query, and SQLite forgets the setting between connections, so this is the right place for it.

Check it worked

flutter test ends with All tests passed! and +2. To see the foreign key test do its work, comment out the customStatement line in database.dart and run the test file again: the second test fails because SQLite accepted the entry for customer 99. Put the line back before you continue.

Step 4 · Show live data with watch() and a StreamBuilder

watchBalances() returns a stream. Drift runs the query once when something listens, then again after every insert, update or delete through Drift that touches customers or tab_entries, and sends the new list down the stream. The screen never needs to be told to refresh.

Open the stream once, in the state object, not inside build: build can run many times a second, and each call would start a new query. A small dialog adds customers:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/tab_screen.dart <<'DART'
import 'package:material_ui/material_ui.dart';
import 'package:tab_book/data/tab_dao.dart';

String formatAmount(int cents) => (cents / 100).toStringAsFixed(2);

class TabScreen extends StatefulWidget {
  const TabScreen({super.key, required this.dao});

  final TabDao dao;

  @override
  State<TabScreen> createState() => _TabScreenState();
}

class _TabScreenState extends State<TabScreen> {
  late final Stream<List<CustomerBalance>> _balances = widget.dao
      .watchBalances();

  Future<void> _addCustomer() async {
    final name = await showDialog<String>(
      context: context,
      builder: (context) => const _NameDialog(),
    );
    if (name == null || name.trim().isEmpty) return;
    await widget.dao.addCustomer(name.trim());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Tab book')),
      body: StreamBuilder<List<CustomerBalance>>(
        stream: _balances,
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text('Could not load: ${snapshot.error}'));
          }
          final balances = snapshot.data;
          if (balances == null) {
            return const Center(child: CircularProgressIndicator());
          }
          if (balances.isEmpty) {
            return const Center(child: Text('No customers yet'));
          }
          return ListView.builder(
            itemCount: balances.length,
            itemBuilder: (context, index) {
              final balance = balances[index];
              final phone = balance.customer.phone;
              return ListTile(
                title: Text(balance.customer.name),
                subtitle: phone == null ? null : Text(phone),
                trailing: Text(formatAmount(balance.owedCents)),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addCustomer,
        tooltip: 'Add customer',
        child: const Icon(Icons.person_add),
      ),
    );
  }
}

class _NameDialog extends StatefulWidget {
  const _NameDialog();

  @override
  State<_NameDialog> createState() => _NameDialogState();
}

class _NameDialogState extends State<_NameDialog> {
  final TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('New customer'),
      content: TextField(
        controller: _controller,
        autofocus: true,
        decoration: const InputDecoration(labelText: 'Name'),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        FilledButton(
          onPressed: () => Navigator.pop(context, _controller.text),
          child: const Text('Save'),
        ),
      ],
    );
  }
}
DART

The app itself opens a real file. driftDatabase from drift_flutter picks a path, opens SQLite on a background isolate so queries never stall the interface, and works the same on Android and iOS. The Drift documentation suggests the application support directory rather than the default documents directory, because the support directory is private to the app and not shown to the user. This is the only file under lib/data that imports Flutter packages:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/open_connection.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
import 'package:path_provider/path_provider.dart';

QueryExecutor openConnection() {
  return driftDatabase(
    name: 'tab_book',
    native: const DriftNativeOptions(
      databaseDirectory: getApplicationSupportDirectory,
    ),
  );
}
DART
cat > lib/main.dart <<'DART'
import 'package:material_ui/material_ui.dart';
import 'package:tab_book/data/database.dart';
import 'package:tab_book/data/open_connection.dart';
import 'package:tab_book/tab_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  final database = AppDatabase(openConnection());
  runApp(TabBookApp(database: database));
}

class TabBookApp extends StatelessWidget {
  const TabBookApp({super.key, required this.database});

  final AppDatabase database;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tab book',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
      ),
      home: TabScreen(dao: database.tabDao),
    );
  }
}
DART

Create one AppDatabase for the whole app and pass it down, as main does here. Two instances on the same file each keep their own stream bookkeeping, so a write through one would not refresh a screen watching the other, and Drift prints a warning in debug builds.

Now prove the stream redraws the screen. This widget test writes to the database directly, never touching the widget, and expects the total on screen to change:

Bash
cd ~/flutter-drift-demo/tab_book
cat > test/tab_screen_test.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tab_book/data/database.dart';
import 'package:tab_book/tab_screen.dart';

void main() {
  testWidgets('the list redraws when the table changes', (tester) async {
    final db = AppDatabase(
      DatabaseConnection(
        NativeDatabase.memory(),
        closeStreamsSynchronously: true,
      ),
    );
    final amina = await db.tabDao.addCustomer('Amina');
    await db.tabDao.addEntry(customerId: amina, item: 'Rice 2kg', amountCents: 15000);

    await tester.pumpWidget(MaterialApp(home: TabScreen(dao: db.tabDao)));
    await tester.pumpAndSettle();

    expect(find.text('Amina'), findsOneWidget);
    expect(find.text('150.00'), findsOneWidget);

    await db.tabDao.addEntry(customerId: amina, item: 'Milk 500ml', amountCents: 5000);
    await tester.pumpAndSettle();

    expect(find.text('200.00'), findsOneWidget);
    expect(find.text('150.00'), findsNothing);

    await tester.pumpWidget(const SizedBox());
    await db.close();
  });
}
DART
flutter test
flutter analyze

The test replaces the screen with an empty SizedBox before closing the database, so the stream's listener is gone before the database shuts down.

Check it worked

flutter test runs all three tests and ends with All tests passed!, and flutter analyze reports No issues found!. The widget test passing is the proof that matters: nothing called setState, yet the total went from 150.00 to 200.00 because the insert re-ran the watched query.

Step 5 · Change the schema and write a migration

Your first users now have the app, and their phones hold version 1 of the database. The shopkeeper asks for a way to mark a customer's tab as paid without deleting the history. That needs a new column, paid_at, and a migration that adds it to existing databases without losing a single entry.

Drift's tools work from snapshots of every schema version you have released. Save version 1 before you change anything:

Bash
cd ~/flutter-drift-demo/tab_book
mkdir -p drift_schemas
dart run drift_dev schema dump lib/data/database.dart drift_schemas/
ls drift_schemas

ls shows drift_schema_v1.json, a description of every table and column in version 1. Commit this folder with your code; you will need every version in it for as long as some phone might still be on that version.

Now make the change. Add a nullable paidAt column (an entry with no payment date is still owed) and bump schemaVersion to 2:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/tables.dart <<'DART'
import 'package:drift/drift.dart';

class Customers extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text().withLength(min: 1, max: 80)();
  TextColumn get phone => text().nullable()();
}

class TabEntries extends Table {
  IntColumn get id => integer().autoIncrement()();
  IntColumn get customerId => integer().references(Customers, #id)();
  TextColumn get item => text().withLength(min: 1, max: 120)();
  IntColumn get amountCents => integer()();
  DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
  DateTimeColumn get paidAt => dateTime().nullable()();
}
DART
cat > lib/data/database.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/tab_dao.dart';
import 'package:tab_book/data/tables.dart';

part 'database.g.dart';

@DriftDatabase(tables: [Customers, TabEntries], daos: [TabDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.e);

  @override
  int get schemaVersion => 2;

  @override
  MigrationStrategy get migration => MigrationStrategy(
    beforeOpen: (details) async {
      await customStatement('PRAGMA foreign_keys = ON');
    },
  );
}
DART
dart run build_runner build
dart run drift_dev schema dump lib/data/database.dart drift_schemas/
dart run drift_dev schema steps drift_schemas/ lib/data/schema_versions.dart

The second dump writes drift_schema_v2.json. schema steps reads both snapshots and generates lib/data/schema_versions.dart, which contains a stepByStep helper with one named callback per upgrade, here from1To2. Each callback receives the schema exactly as it was at its target version, so a step written today still compiles after a later release renames or drops that column.

Fill in the step. The new column is nullable, so adding it is one ALTER TABLE ... ADD COLUMN, and every existing entry gets NULL, which means "still owed", exactly the meaning you want:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/database.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/schema_versions.dart';
import 'package:tab_book/data/tab_dao.dart';
import 'package:tab_book/data/tables.dart';

part 'database.g.dart';

@DriftDatabase(tables: [Customers, TabEntries], daos: [TabDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.e);

  @override
  int get schemaVersion => 2;

  @override
  MigrationStrategy get migration => MigrationStrategy(
    onUpgrade: stepByStep(
      from1To2: (m, schema) async {
        await m.addColumn(schema.tabEntries, schema.tabEntries.paidAt);
      },
    ),
    beforeOpen: (details) async {
      await customStatement('PRAGMA foreign_keys = ON');
    },
  );
}
DART

New installs never run onUpgrade: Drift creates every table at the latest version instead. Phones already on version 1 run from1To2 the first time the new release opens the database. Drift does not wrap migrations in a transaction by default; for steps with several statements, the Drift documentation shows how to run each step inside one so a phone that dies halfway through does not end up half-migrated.

Then teach the DAO about payments. Only unpaid entries count towards the balance, and settling a customer stamps all their open entries with today's date:

Bash
cd ~/flutter-drift-demo/tab_book
cat > lib/data/tab_dao.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:tab_book/data/database.dart';
import 'package:tab_book/data/tables.dart';

part 'tab_dao.g.dart';

class CustomerBalance {
  const CustomerBalance(this.customer, this.owedCents);

  final Customer customer;
  final int owedCents;
}

@DriftAccessor(tables: [Customers, TabEntries])
class TabDao extends DatabaseAccessor<AppDatabase> with _$TabDaoMixin {
  TabDao(super.attachedDatabase);

  Future<int> addCustomer(String name, {String? phone}) {
    return into(customers).insert(
      CustomersCompanion.insert(name: name, phone: Value(phone)),
    );
  }

  Future<int> addEntry({
    required int customerId,
    required String item,
    required int amountCents,
  }) {
    return into(tabEntries).insert(
      TabEntriesCompanion.insert(
        customerId: customerId,
        item: item,
        amountCents: amountCents,
      ),
    );
  }

  Future<int> settleCustomer(int customerId) {
    return (update(tabEntries)..where(
          (e) => e.customerId.equals(customerId) & e.paidAt.isNull(),
        ))
        .write(TabEntriesCompanion(paidAt: Value(DateTime.now())));
  }

  Selectable<CustomerBalance> _balances() {
    final owed = tabEntries.amountCents.sum();
    final query =
        select(customers).join([
            leftOuterJoin(
              tabEntries,
              tabEntries.customerId.equalsExp(customers.id) &
                  tabEntries.paidAt.isNull(),
              useColumns: false,
            ),
          ])
          ..addColumns([owed])
          ..groupBy([customers.id])
          ..orderBy([OrderingTerm.asc(customers.name)]);
    return query.map(
      (row) => CustomerBalance(row.readTable(customers), row.read(owed) ?? 0),
    );
  }

  Future<List<CustomerBalance>> balances() => _balances().get();

  Stream<List<CustomerBalance>> watchBalances() => _balances().watch();
}
DART
dart run build_runner build
cat > test/settle_test.dart <<'DART'
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tab_book/data/database.dart';

void main() {
  late AppDatabase db;

  setUp(() {
    db = AppDatabase(
      DatabaseConnection(
        NativeDatabase.memory(),
        closeStreamsSynchronously: true,
      ),
    );
  });

  tearDown(() => db.close());

  test('settling clears what is owed but keeps the history', () async {
    final amina = await db.tabDao.addCustomer('Amina');
    await db.tabDao.addEntry(customerId: amina, item: 'Rice 2kg', amountCents: 15000);
    await db.tabDao.addEntry(customerId: amina, item: 'Sugar 1kg', amountCents: 5000);

    expect(await db.tabDao.settleCustomer(amina), 2);
    await db.tabDao.addEntry(customerId: amina, item: 'Milk 500ml', amountCents: 6000);

    final balances = await db.tabDao.balances();
    expect(balances.single.owedCents, 6000);
    expect(await db.select(db.tabEntries).get(), hasLength(3));
  });
}
DART
flutter test
flutter analyze

The paid condition sits in the join's ON clause, not in a WHERE. A WHERE paid_at IS NULL would drop a fully paid customer from the list altogether; in the ON clause it only drops their paid entries, so the customer still appears with 0.00.

Check it worked

drift_schemas holds drift_schema_v1.json and drift_schema_v2.json, lib/data/schema_versions.dart exists, flutter test passes all four tests and flutter analyze finds no issues. The tests so far all start from an empty version 2 database, though. None of them has opened a version 1 database yet, which is what the next step does.

Step 6 · Test the migration against the old schema

A migration only runs on your users' phones, on their data, once. Test it before it ships. schema generate turns the saved snapshots into test helpers that can create a database at any old version:

Bash
cd ~/flutter-drift-demo/tab_book
dart run drift_dev schema generate drift_schemas/ test/generated_migrations/
ls test/generated_migrations

It writes schema.dart, with a GeneratedHelper that knows every version, plus schema_v1.dart and schema_v2.dart. The test below opens a real version 1 database, fills it with raw SQL as the old app would have, runs your migration through migrateAndValidate, and then reads the data back through the new code. migrateAndValidate also compares every table in the migrated database with the version 2 snapshot and fails on any difference, such as a forgotten column:

Bash
cd ~/flutter-drift-demo/tab_book
cat > test/migration_test.dart <<'DART'
import 'package:drift_dev/api/migrations_native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tab_book/data/database.dart';

import 'generated_migrations/schema.dart';

void main() {
  late SchemaVerifier verifier;

  setUpAll(() {
    verifier = SchemaVerifier(GeneratedHelper());
  });

  test('a new install matches the version 2 snapshot', () async {
    final db = AppDatabase(await verifier.startAt(2));
    await verifier.migrateAndValidate(db, 2);
    await db.close();
  });

  test('upgrading from version 1 keeps every entry as owed', () async {
    final schema = await verifier.schemaAt(1);
    schema.rawDatabase.execute(
      'INSERT INTO customers (id, name) VALUES (?, ?)',
      [1, 'Amina'],
    );
    schema.rawDatabase.execute(
      'INSERT INTO tab_entries (customer_id, item, amount_cents, created_at) '
      'VALUES (?, ?, ?, ?)',
      [1, 'Rice 2kg', 15000, 1767225600],
    );

    final db = AppDatabase(schema.newConnection());
    await verifier.migrateAndValidate(db, 2);

    final entries = await db.select(db.tabEntries).get();
    expect(entries.single.item, 'Rice 2kg');
    expect(entries.single.paidAt, isNull);
    expect((await db.tabDao.balances()).single.owedCents, 15000);
    await db.close();
  });
}
DART
flutter test
flutter analyze

The insert uses ? placeholders with a list of values, the same way you should pass any value into SQL. 1767225600 is 1 January 2026 as Unix seconds, which is how Drift stores DateTime columns unless you configure it to use text.

For the next schema change, repeat the same loop: change the tables, bump schemaVersion, run build_runner, dump the new snapshot, regenerate the steps and test helpers, write the fromNToN+1 step, and add a test that starts at the previous version. Drift's dart run drift_dev make-migrations command can run the dump, steps and test generation in one go once you list the database in build.yaml; the manual commands used here show what it does.

Check it worked

flutter test ends with All tests passed! and +6. Now break the migration on purpose: in database.dart, comment out the m.addColumn line, and run flutter test test/migration_test.dart. The upgrade test fails with a schema mismatch naming the missing paid_at column. That is the failure your users would otherwise have met as a crash on launch. Put the line back and run the tests again before you continue.

Step 7 · Decide what goes in Drift, shared_preferences or secure storage

Drift is the right home for records: rows you query, join, sort or add up, that grow over time and change shape between releases. It is not the right home for everything an app stores.

  • A handful of settings, such as the chosen currency, theme or language, belong in shared_preferences. It stores int, double, bool, String and List<String> values under keys, with no schema or migrations. Its own documentation says writes are not guaranteed to reach the disk, so never use it for data that would hurt to lose, like a customer's tab. Start new code with SharedPreferencesAsync or SharedPreferencesWithCache; the older SharedPreferences class is a legacy API due to be deprecated.
  • Secrets, such as an access token for your sync server or an API key a user pastes in, belong in flutter_secure_storage. It uses the iOS Keychain, and on Android encrypts values with keys held by the system keystore. Never put a secret in SQLite or shared_preferences, which are plain files inside the app's folder, and never hard-code one in Dart, where anyone can pull it out of the app package.
  • A whole database that must be encrypted, for example health records, is a different case again. sqlite3 can bundle SQLite3MultipleCiphers or SQLCipher instead of plain SQLite through a setting in pubspec.yaml; read the encryption page of the Drift documentation before you choose, since both have their own licences, and keep the database key itself in secure storage.

On a low-end Android phone with little free space, every store you add costs storage, so keep each one to what it is for: preferences small, secrets few, records in the database where you can clean up old ones with a DELETE when they are no longer needed.

Check it worked

Write down every value your app stores and sort each into one of the three. For the credit book, the customers and entries go in Drift, a currency code such as KES or NGN would go in shared_preferences, and a token for a future sync server would go in flutter_secure_storage. If anything secret is on the Drift or preferences list, move it before you ship.

Step 8 · Run it on a phone and clean up

With an emulator, simulator or phone connected, run the app:

Bash
cd ~/flutter-drift-demo/tab_book
flutter run

Tap the add button, add two customers, then close the app completely and open it again. The customers are still there, read from the tab_book database in the app's support directory. To try a settle button, call widget.dao.settleCustomer(balance.customer.id) from the ListTile's onLongPress in tab_screen.dart; because the screen watches the query, the total drops to 0.00 without any extra code.

While you are developing, uninstalling the app is the quickest way to start again from an empty database. On Android, a reinstall can restore the old database from the system's automatic backup, so if old data reappears after a reinstall, clear the app's storage in its system settings instead.

Bundling SQLite adds a native library to the app for each processor type. If you hand out APKs directly rather than through Google Play, build one per processor type with flutter build apk --split-per-abi so people on prepaid data download only what their phone needs.

When you are finished, stop the app with q. The next command deletes the practice project, including its database snapshots and tests:

Bash
cd ~
rm -rf ~/flutter-drift-demo

Check it worked

On the phone, the customers you added survive a full restart of the app. On your computer, ls ~/flutter-drift-demo reports that there is no such file or directory, and the Flutter SDK in ~/develop/flutter is untouched. Uninstall the app from the phone to remove its database.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.