Sub topic 12
Hiding storage behind a repository
This chapter assumes you can write Dart classes with null safety, use async and await, and build a simple stateful Flutter widget. It also assumes you have the Note model with toMap and fromMap, and the openNotesDatabase function from the SQLite chapters. The code here reuses both.
Why put a repository in front of storage
A repository is a class that offers your app a small set of operations on one kind of data, such as "add a note" or "list all notes". The rest of the app calls these operations. It does not know whether the data lives in SQLite, a JSON file or memory.
Without this boundary, widgets call db.query and db.insert directly. That causes three problems:
- Storage details spread through the UI. Table names, column names and
whereArgsappear in many widgets. Changing the schema means editing all of them. - Tests need a real database. A widget that opens SQLite cannot run in a plain unit test.
- Switching storage is expensive. Moving from
sqflitetodriftmeans rewriting every caller.
A repository fixes these by giving your code one place that knows about storage. The cost is one extra class per kind of data, so use it where the data matters.
Define the interface first
Start from what the app needs, not from what the database offers. The interface uses only your own types, Note and int.
abstract interface class NoteRepository {
Future<List<Note>> all();
Future<Note?> byId(int id);
Future<Note> add(Note note);
Future<void> remove(int id);
}Some design choices are worth making deliberately:
byIdreturnsnullwhen no row exists. A missing note is a normal outcome, so callers should not need atry/catchfor it.addreturns the savedNote, including the id the database generated. Callers never handle raw row ids.removereturns nothing. Deleting an id that does not exist is not an error for the app.- No method mentions
Database,Map, SQL or file paths.
The SQLite implementation
The implementation takes an open Database in its constructor. It does not open the database itself, so the owner of the app decides when and how the database is created.
import 'package:sqflite/sqflite.dart';
class SqliteNoteRepository implements NoteRepository {
SqliteNoteRepository(this._db);
final Database _db;
@override
Future<List<Note>> all() async {
final rows = await _db.query('notes', orderBy: 'id DESC');
return rows.map(Note.fromMap).toList();
}
@override
Future<Note?> byId(int id) async {
final rows = await _db.query(
'notes',
where: 'id = ?',
whereArgs: [id],
limit: 1,
);
if (rows.isEmpty) return null;
return Note.fromMap(rows.first);
}
@override
Future<Note> add(Note note) async {
final id = await _db.insert('notes', note.toMap()..remove('id'));
return Note(id: id, title: note.title, body: note.body);
}
@override
Future<void> remove(int id) async {
await _db.delete('notes', where: 'id = ?', whereArgs: [id]);
}
}Every user-supplied value goes through whereArgs. The SQL stays inside this class, so it is the only place you need to audit.
An in-memory implementation
A second implementation of the same interface keeps notes in a Map. It needs no plugin and no device, and it runs in microseconds.
class InMemoryNoteRepository implements NoteRepository {
final Map<int, Note> _notes = {};
int _nextId = 1;
@override
Future<List<Note>> all() async => _notes.values.toList().reversed.toList();
@override
Future<Note?> byId(int id) async => _notes[id];
@override
Future<Note> add(Note note) async {
final saved = Note(id: _nextId++, title: note.title, body: note.body);
_notes[saved.id!] = saved;
return saved;
}
@override
Future<void> remove(int id) async {
_notes.remove(id);
}
}A Map keeps insertion order, so reversing the values gives newest first. That matches ORDER BY id DESC in the SQLite version. The fake must behave like the real one in every way the app can observe. If it orders results differently, tests pass while the app misbehaves.
Passing the repository to the UI
Give each widget its repository through the constructor. This is called constructor injection. It is the simplest way to let tests and production supply different implementations, and it needs no package.
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final db = await openNotesDatabase();
runApp(NotesApp(repository: SqliteNoteRepository(db)));
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key, required this.repository});
final NoteRepository repository;
@override
Widget build(BuildContext context) {
return MaterialApp(home: NotesPage(repository: repository));
}
}
class NotesPage extends StatefulWidget {
const NotesPage({super.key, required this.repository});
final NoteRepository repository;
@override
State<NotesPage> createState() => _NotesPageState();
}
class _NotesPageState extends State<NotesPage> {
late Future<List<Note>> _notes = widget.repository.all();
Future<void> _addNote() async {
await widget.repository.add(const Note(title: 'New note'));
if (!mounted) return;
setState(() => _notes = widget.repository.all());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Notes')),
floatingActionButton: FloatingActionButton(
onPressed: _addNote,
child: const Icon(Icons.add),
),
body: FutureBuilder<List<Note>>(
future: _notes,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final note in snapshot.data!)
ListTile(title: Text(note.title)),
],
);
},
),
);
}
}The page never imports sqflite. The database is opened once in main, before runApp, so no widget has to wait for initialization. That also avoids opening the same file twice.
Testing against the repository
A test for any code that uses NoteRepository can use the in-memory version directly:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('add assigns ids and all returns newest first', () async {
final repo = InMemoryNoteRepository();
final first = await repo.add(const Note(title: 'a'));
await repo.add(const Note(title: 'b'));
expect(first.id, 1);
expect((await repo.all()).map((n) => n.title), ['b', 'a']);
});
test('byId returns null after remove', () async {
final repo = InMemoryNoteRepository();
final saved = await repo.add(const Note(title: 'a'));
await repo.remove(saved.id!);
expect(await repo.byId(saved.id!), isNull);
});
}You can wrap the same assertions in a function that takes a repository, then run it against both implementations. This is called a contract test. It guards against the fake and the real class drifting apart. To run the SQLite version outside a device, add sqflite_common_ffi as a dev dependency, call sqfliteFfiInit(), and set databaseFactory = databaseFactoryFfi before opening an in-memory database.
Common errors and edge cases
- Leaking the storage type. A method such as
Future<List<Map<String, Object?>>> rawNotes()ties every caller to SQLite rows. Return domain objects. - Leaking storage exceptions. A
DatabaseExceptionthrown fromaddreaches the UI, which then depends onsqflite. For failures the app can act on, catch them in the repository and throw your own type, such asNoteStorageException. Do not wrap everything, because a bug is better surfaced than hidden. - Opening the database inside each call. Repeated
openDatabasecalls are wasteful and make ordering bugs likely. Open once and share theDatabase. - A fake that is too forgiving. If the in-memory
addaccepts input the real database rejects, such as aNOT NULLviolation, tests will not catch the bug. Mirror the important constraints. - Ids chosen by callers.
addstripsidso SQLite generates it. Letting callers set ids invites collisions withAUTOINCREMENT. - Over-abstracting. An interface with one implementation and no tests is only ceremony. Add the boundary when you have a second implementation, usually the fake, or a real chance of changing storage.
Beyond one repository
A repository can hold more than one storage mechanism. For example, a SettingsRepository might read a theme from shared_preferences and a token from flutter_secure_storage, while exposing Future<ThemeMode> theme() and Future<String?> token(). The caller sees one class, and each kind of data still goes to the store that suits it.
Exercise
You add a method Future<List<Note>> search(String title) to NoteRepository. Which two classes must change, and how should the SQLite version pass the title to the database?
Show answer
SqliteNoteRepository and InMemoryNoteRepository must both implement it, or they will not compile. The SQLite version should call _db.query('notes', where: 'title = ?', whereArgs: [title]) and map the rows with Note.fromMap. It must not put the title into the SQL string by interpolation, which would allow SQL injection. The in-memory version should filter _notes.values with where((n) => n.title == title), so both return the same results.
Exercise
A widget test passes using InMemoryNoteRepository, but the app crashes on a device when a note has no title. What likely caused the mismatch, and how do you prevent it?
Show answer
The notes table declares title TEXT NOT NULL, so SQLite rejects the insert, but the in-memory fake accepted it. The fake is too forgiving. Prevent this by making the fake enforce the same rule, for example by validating the title in add. You can also run a contract test against both implementations, using sqflite_common_ffi for the SQLite one.