Local database

Flutter tips Published on

Work Offline with Local Database

Want your Flutter app to work even when there's no internet? A local database is the answer! This guide shows you how to set one up using the Drift package.

1 - Get the Drift Package

First, you need to add the necessary packages to your project. Open your terminal in your project folder and run these commands:

dart pub add drift
dart pub add drift_flutter
dart pub add drift_dev

This adds the main drift package, one for Flutter integration, and one for development tools (like code generation).

2 - Set Up Your Database

Create a Dart file for your database. You'll define a class that extends _$Database. Use the @DriftDatabase annotation to tell Drift which tables belong to this database.

(tables: [
  TaskTable,
])
class Database extends _$Database {
  Database([QueryExecutor? e]) : super(
    e ??
      DriftDatabase(
        name: 'todo-app',
        native: const DriftNativeOptions(
          databaseDirectory: getApplicationSupportDirectory,
        ),
      ),
  );

  
  int get schemaVersion => 2; // Your database version

  
  MigrationStrategy get migration {
    return MigrationStrategy(
      onCreate: (m) async {
        await m.createAll();
      },
      // Push any migration here if version is new
    );
  }
}

This code sets up your database with a specific name and location, defines its schema version, and handles initial creation.

3 - Define Your Tables

Each table in your database needs a corresponding Dart class that extends Table. Use the @DataClassName annotation to give the generated data class a custom name (like 'TaskEntry' for 'TaskTable'). Define your columns using types like IntColumn and TextColumn.

('TaskEntry')
class TaskTable extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get description => text()();

  // Add your queries like this
  static Stream<List<TaskEntry>> getAllItems(Database database) =>
      database.select(database.taskTable).watch();
}

You can also add static methods here to define common queries for your table.

4 - Configure the Build File

Drift uses code generation to create a lot of the necessary code for you. You need to configure the build.yaml file at the root of your Flutter project to tell the build runner where to find your database definition.

targets:
  $default:
    builders:
      ## Add this
      drift_dev:
        # These options change how drift generates code
        options:
          databases:
            default: lib/modules/drift/database.dart
            sql:
              dialect: sqlite
              options:
                version: "3.38"
                modules: [fts5]

After setting this up, you need to run the build runner command to generate the database schema and other necessary code.

Run the Build Runner

Make sure to run this command in your project directory whenever you make changes to your database or tables:

Build Runner Command
dart run build_runner build

This command generates the code needed to interact with your database based on your definitions.

Save 3 months of work

Create your app using our 6 years of making Flutter apps and more than 50+ apps

kickstarter for flutter apps

Frequently Asked Questions

Why would I use a local database in my Flutter app?

A local database lets your app store and retrieve data directly on the user's device, which is great for making your app work offline or providing faster access to frequently used data.

What is the Drift package?

Drift is a reactive database framework for Flutter and Dart. It makes working with SQLite databases easier by providing a type-safe way to define your database, tables, and run queries.

What does the `build.yaml` file do?

The `build.yaml` file is used to configure build tools in Dart and Flutter. In this case, it tells the `drift_dev` builder where to find your database definition file so it can generate the necessary code.

Do I need to run the build runner every time I change my database?

Yes, if you change your table definitions, add new tables, or modify your database class, you need to run the build runner command (`dart run build_runner build`) to update the generated code.

Read more
You may also be interested in
Go Beyond Material: Add Custom Colors in your Flutter Theme  blog card image
Go Beyond Material: Add Custom Colors in your Flutter Theme
Published on 2025-05-12T08:49:42.146Z
Automatically create a new Apple Store version  blog card image
Automatically create a new Apple Store version
Published on 2025-05-12T09:03:39.549Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved