Sub topic 3
Changing the schema with versions and migrations
This chapter assumes you know Dart classes, null safety, Future, async and await, and how to add packages in pubspec.yaml. You should also have a working sqflite database with a notes table.
Schema versions
A schema is the table layout inside a database. sqflite stores a version number in the database file. When openDatabase runs with a version higher than the stored number, sqflite calls onUpgrade. When the file does not exist yet, it calls onCreate instead.
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: 2,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT, '
'pinned INTEGER NOT NULL DEFAULT 0)',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
);
}
},
);
}The onCreate block builds the full version 2 layout for new installs. The onUpgrade block applies one change to older installs.
::: callout warning Never edit an old migration step after release. Add a new if block for each new version instead. Otherwise, devices that already ran the old step keep a different schema. :::
Type-safe databases with drift
drift is a package that generates Dart classes from table definitions. Column names and types are checked at compile time, so a typo fails the build instead of failing at runtime. Use drift when raw SQL strings become hard to maintain. For a small schema, sqflite is simpler.
Embedded NoSQL and object stores
Embedded NoSQL stores, such as Hive or Isar, save objects without fixed tables. They are quick to set up and work well for caches. They support fewer queries than SQL, and migrations need your own code. Choose them when your data has no joins and you do not need strict schemas.
Hiding storage behind a repository
A repository is a class that exposes data operations and hides the storage engine. Callers depend on the interface, so you can swap sqflite for a fake in tests.
abstract class NotesRepository {
Future<List<Note>> loadNotes();
Future<void> saveNotes(List<Note> notes);
}
class FakeNotesRepository implements NotesRepository {
List<Note> _notes = [];
@override
Future<List<Note>> loadNotes() async => List.of(_notes);
@override
Future<void> saveNotes(List<Note> notes) async => _notes = List.of(notes);
}This example assumes the Note class from your model code.
Testing storage code
Tests should not touch a real device. For shared_preferences, seed the values in memory:
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('defaults to false when nothing is stored', () async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
expect(prefs.getBool('dark_mode') ?? false, isFalse);
});
}Choosing the right option
| Data | Suitable storage |
|---|---|
| Small settings | shared_preferences |
| Tokens and passwords | flutter_secure_storage |
| Documents or JSON exports | Files via path_provider |
| Many rows with queries | sqflite or drift |
| Objects without joins | Embedded NoSQL store |
Exercise
A release added a pinned column to the notes table, but users who installed version 1 report "no such column: pinned". What is the most likely cause, and how do you fix it?
Show answer
The version number was not raised, or the upgrade step was missing, so onUpgrade never added the column for existing installs. Raise version to 2, add an onUpgrade branch that runs ALTER TABLE for oldVersion < 2, and keep the onCreate schema in sync.