Sub topic 7
Opening a SQLite Database with sqflite
This chapter assumes you know basic Dart classes, null safety, Future, async, and await. You should also know how to add packages to pubspec.yaml and build a simple Flutter screen.
SQLite is a relational database stored in a file on the device. A relational database stores data in tables. Each table contains rows, and each row contains columns. SQLite is a good fit when an app has many records, related data, or queries such as search, sorting, and filtering.
The sqflite package connects Flutter to SQLite. The path package helps build a platform-safe file path.
Add the packages
Add these dependencies to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
path: ^1.9.0
sqflite: ^2.3.3+1Run flutter pub get after saving the file.
Open the database
A database has a file path and a schema. A schema describes the tables and columns in the database.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<Database> openNotesDatabase() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 1,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
);
},
);
}getDatabasesPath() returns the platform-specific directory intended for database files. join combines that directory with the file name without making assumptions about path separators.
openDatabase opens the existing notes.db file or creates it when the file does not exist. The returned Database object provides methods for creating tables and running queries.
The version value is the schema version, not the app version. SQLite passes this value to the lifecycle callbacks. When a database is created for the first time, onCreate runs. The SQL statement creates a notes table with three columns:
idis an automatically generated integer primary key.titleis required because it has theNOT NULLconstraint.bodyis optional because it has noNOT NULLconstraint.
Understand the open lifecycle
The database file remains on the device between app launches. Therefore, onCreate does not run every time openNotesDatabase is called. It runs only when SQLite creates that file.
If you later change the table, increase version and add an onUpgrade callback. Existing users need a migration because their database already exists. New users still need onCreate to create the latest complete schema.
Manage the database instance
Database operations are asynchronous because reading from storage can take time. Store the opened database and reuse it rather than opening a new connection for every button press. Close it when the owning service is permanently disposed.
A database is not automatically a good choice for every value. Use preferences for small independent settings, files for serialized documents, and secure storage for secrets. SQLite is useful when the data has structure and needs queries.
Exercise
When does onCreate run, and what should happen if an existing table needs a new column?
Show answer
onCreate runs only when the database file is first created. Increase the database version and use onUpgrade to migrate existing databases.