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.