Sub topic 7
Opening a SQLite database with sqflite
This chapter assumes you know basic Dart, async/await, and how to add a package in pubspec.yaml. You should also have seen path_provider and file storage in the earlier chapters. By the end you will be able to open a SQLite database, create its first table, and share one connection across your app. Inserting and querying rows is the next chapter. Schema changes are covered in a later one. This chapter only touches on both.
What SQLite gives you
SQLite is a relational database engine that lives inside your app as a library. There is no server. The whole database is one file on the device. You describe data as tables with typed columns and read it back with SQL.
Choose it over preferences or JSON files when you need one of these:
- Many records, where loading everything into memory is wasteful.
- Filtering, sorting or counting without writing the loops yourself.
- Relations between records, such as notes that belong to a notebook.
- Several changes that must succeed or fail together (transactions).
The sqflite package wraps the SQLite library that ships with Android, iOS and macOS. Calls cross a platform channel to native code, so every database method returns a Future.
Adding the packages
dependencies:
flutter:
sdk: flutter
sqflite: ^2.3.0
path: ^1.9.0path provides join, which builds file paths with the correct separator. Run flutter pub get after editing. If a newer version of either package is available, use it.
Opening a database
Opening requires a file path. getDatabasesPath() returns the platform's default directory for database files. On Android this is the app's databases folder. On iOS and macOS it is a folder inside the app's sandbox.
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)',
);
},
);
}openDatabase does three things:
- It creates the file if it does not exist, or opens it if it does.
- It compares the
versionyou pass with the version stored in the file. - It calls the callbacks that match the situation, then returns a
Databaseobject.
The onCreate callback runs only when the file did not exist. It is the right place for CREATE TABLE statements. If you add a table to this callback later, existing installs will not get it, because their file already exists. That is the reason migrations exist.
The open sequence
openDatabase can call up to four callbacks. They run in a fixed order, and which ones run depends on the stored version.
| Callback | When it runs | Typical use |
|---|---|---|
| `onConfigure` | First, before anything else | `PRAGMA` settings such as foreign keys |
| `onCreate` | The file did not exist | Create tables |
| `onUpgrade` | Stored version is lower than `version` | `ALTER TABLE`, data fixes |
| `onDowngrade` | Stored version is higher than `version` | Rare. Usually reset or refuse |
| `onOpen` | Last, on every open | Sanity checks, logging |
onCreate, onUpgrade and onDowngrade run inside a transaction. If one of them throws, the changes are rolled back and openDatabase fails with the same error.
Turning on foreign keys
SQLite ignores FOREIGN KEY constraints unless you enable them for each connection. Do this in onConfigure, so it takes effect before onCreate or onUpgrade run.
Future<Database> openConfiguredDatabase() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 1,
onConfigure: (db) async {
await db.execute('PRAGMA foreign_keys = ON');
},
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
);
},
);
}If you skip this, a delete that should be blocked by a foreign key will succeed silently. The bug only shows up when orphaned rows cause problems later.
Sharing one connection
Opening a database is not free, and many parts of an app need it. The common approach is one object that opens the database once and hands out the same Database afterwards.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class NotesDatabase {
NotesDatabase._();
static final NotesDatabase instance = NotesDatabase._();
Future<Database>? _opening;
Future<Database> get database {
return _opening ??= _open().catchError((Object error) {
_opening = null;
throw error;
});
}
Future<Database> _open() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 1,
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
);
},
);
}
Future<void> close() async {
final opening = _opening;
_opening = null;
if (opening != null) {
await (await opening).close();
}
}
}Two details in this class matter:
- It caches the
Future, not the finishedDatabase. If two widgets calldatabasein the same frame, a cache of the finished object would still be empty for both, and each would start its own open. Caching theFuturemakes the second caller wait for the first. - If opening fails, the cached
Futureis cleared. Otherwise every later call would receive the same failed result and the app could never recover without a restart.
By default, sqflite also returns the same underlying connection when you open the same path twice. You should still not rely on that. Treat a single owner of the connection as the design.
Using it from main
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final db = await NotesDatabase.instance.database;
final tables = await db.rawQuery(
"SELECT name FROM sqlite_master WHERE type = 'table'",
);
debugPrint('Tables: $tables');
runApp(const SizedBox.shrink());
}WidgetsFlutterBinding.ensureInitialized() is required before any platform channel call that happens before runApp. Without it, the first database call can fail with a binding error. The query on sqlite_master lists the tables in the file. You should see notes and an internal table, sqlite_sequence, which SQLite creates for AUTOINCREMENT.
You do not have to open the database at startup. Opening it lazily on first use is fine, as long as the whole app goes through NotesDatabase.instance.
Column types and what Dart gets back
SQLite has five storage classes. Dart values map onto them like this:
| SQLite type | Dart type | Notes |
|---|---|---|
| `INTEGER` | `int` | Also used for booleans: `0` is false, `1` is true |
| `REAL` | `double` | |
| `TEXT` | `String` | Store dates as ISO 8601 strings |
| `BLOB` | `Uint8List` | Avoid large files. Store a file path instead |
| `NULL` | `null` | Column must not be `NOT NULL` |
There is no bool or DateTime column. Convert them in your model's toMap and fromMap, as in the serialization chapter. For example, store pinned as INTEGER and read it back with map['pinned'] == 1. Store createdAt.toIso8601String() as TEXT, or millisecondsSinceEpoch as INTEGER. SQLite will accept a string in an INTEGER column without complaint, so a wrong conversion shows up only when you read the value.
Platforms and test setups
- Android, iOS, macOS:
sqfliteworks as shown. - Windows and Linux: add
sqflite_common_ffiand set the database factory before opening anything. Desktop builds also need the SQLite library available at runtime. The package documentation lists the setup. - Web:
sqflitedoes not run in a browser. Use a different storage option there.
import 'dart:io';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
void initDatabaseFactory() {
if (Platform.isWindows || Platform.isLinux) {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
}
}Call initDatabaseFactory() at the top of main, before the first openDatabase.
The same package helps in unit tests on your development machine. Call sqfliteFfiInit(), set databaseFactory = databaseFactoryFfi, and open with the special path inMemoryDatabasePath. You get a real SQLite engine and an empty database that disappears when closed. The testing chapter returns to this.
Common mistakes
- Editing
onCreateand expecting existing users to change.onCreateruns once per file. Raiseversionand addonUpgradefor existing installs. - Forgetting
awaitonexecute. The statement may run after you read, which gives missing tables or empty results. - Creating a new
Databasefor every operation. It is slow, and it multiplies the places that must close it. Share one connection. - Deleting the file by hand during development and wondering why the schema is stale. The old file keeps its stored version. Uninstall the app, or call
deleteDatabase(path), to start from nothing. - Closing the database in a widget's
dispose. Other parts of the app may still be using it. Close it only when the whole app is shutting down, which is rare. Mobile operating systems end the process on their own.
Exercise
A teammate adds pinned INTEGER NOT NULL DEFAULT 0 to the CREATE TABLE statement in onCreate and ships the update without changing version. Testers who installed the app earlier report that pinning notes crashes, but a fresh install works. Why does this happen, and what is the minimal fix?
Show answer
onCreate only runs when the database file does not exist. Existing installs already have the file with the old schema, and the stored version still equals version: 1, so no callback adds the column. Fresh installs create the table with pinned. The fix is to raise version to 2, keep the new column in onCreate, and add an onUpgrade that runs ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0 when oldVersion < 2.
Exercise
In the NotesDatabase class, why does the code cache a Future<Database>? instead of a Database?, and why does it set _opening back to null when opening fails?
Show answer
Two callers can ask for the database before the first open has finished. A cached Database? would still be null for both, so each would start its own open. A cached Future lets the second caller wait for the first one's result. If the open fails and the failed Future stayed cached, every later call would receive the same error, so the app could not retry. Clearing it on failure allows a new attempt.