Sub topic 12
Hiding Storage Behind a Repository
This chapter assumes basic Dart classes, null safety, Future, async and await, Flutter widgets, and package setup in pubspec.yaml. It also assumes that you have seen a Note model and basic SQLite operations with sqflite.
A repository is a class that provides data operations without exposing how the data is stored. The user interface asks for notes through methods such as listNotes() and addNote(). It does not know whether those methods use SQLite, a file, a web service, or memory.
This separation gives each part of the app one job:
- Widgets display state and respond to user actions.
- A repository coordinates reading and writing data.
- A storage implementation talks to SQLite or another storage system.
- A model represents the data used by the rest of the app.
Define the repository contract
Start with an interface. In Dart, an abstract class can define the operations that a repository must provide.
import 'package:sqflite/sqflite.dart';
class Note {
const Note({
this.id,
required this.title,
this.body,
});
final int? id;
final String title;
final String? body;
factory Note.fromMap(Map<String, Object?> map) {
return Note(
id: map['id'] as int?,
title: map['title'] as String,
body: map['body'] as String?,
);
}
}
abstract interface class NoteRepository {
Future<List<Note>> listNotes();
Future<int> addNote(Note note);
Future<int> deleteNote(int id);
}The interface is the repository's contract. Code that uses NoteRepository depends on these methods, not on sqflite.
Implement the contract with SQLite
Inject the database into the repository. Dependency injection means giving an object the services it needs instead of creating those services inside the object.
class SqliteNoteRepository implements NoteRepository {
SqliteNoteRepository(this.db);
final Database db;
@override
Future<List<Note>> listNotes() async {
final rows = await db.query(
'notes',
orderBy: 'id DESC',
);
return rows.map(Note.fromMap).toList();
}
@override
Future<int> addNote(Note note) {
return db.insert(
'notes',
<String, Object?>{
'title': note.title,
'body': note.body,
},
);
}
@override
Future<int> deleteNote(int id) {
return db.delete(
'notes',
where: 'id = ?',
whereArgs: <Object?>[id],
);
}
}The repository contains SQL-related details, including table names and parameter placeholders. A widget can use the same contract without knowing any of them.
flowchart TD
A[Flutter widget] --> B[NoteRepository contract]
B --> C[SqliteNoteRepository]
C --> D[sqflite Database]
D --> E[notes table]Supply the repository to the app
Create the database near the application boundary, then pass the repository to the screen or state-management layer.
final database = await openNotesDatabase();
final repository = SqliteNoteRepository(database);
// Pass repository to a page, controller, or provider.
final notes = await repository.listNotes();A state-management package can expose the repository to many widgets. The important rule is that widgets depend on NoteRepository, not directly on Database.
Test with an in-memory implementation
A second implementation can store notes in memory. It is useful for unit tests because it avoids a device, database file, and platform setup.
class InMemoryNoteRepository implements NoteRepository {
final List<Note> _notes = <Note>[];
int _nextId = 1;
@override
Future<List<Note>> listNotes() async {
return List<Note>.unmodifiable(_notes);
}
@override
Future<int> addNote(Note note) async {
final id = _nextId++;
_notes.add(Note(id: id, title: note.title, body: note.body));
return id;
}
@override
Future<int> deleteNote(int id) async {
final before = _notes.length;
_notes.removeWhere((note) => note.id == id);
return before - _notes.length;
}
}A test can now use InMemoryNoteRepository and verify application behavior. The same application code can later receive SqliteNoteRepository.
Common errors
- Putting SQL directly in widgets makes storage difficult to replace.
- Creating a new database connection inside every repository method wastes resources.
- Returning raw database maps forces callers to understand the storage schema.
- Giving the in-memory fake different behavior from SQLite can hide bugs. Keep both implementations aligned with the contract.
- A repository should not become a second application layer containing unrelated validation, navigation, and widget state.
Exercise
Why does a widget depend on NoteRepository instead of SqliteNoteRepository?
Show answer
The widget needs data operations, not SQLite details. Depending on the contract makes the widget easier to test and lets the storage implementation change without changing the widget.