Sub topic 6
A Token Repository Around the Storage
Assume you know Dart classes, async and await, Flutter packages, and the basic role of authentication tokens. This chapter focuses on placing flutter_secure_storage behind a small repository so the rest of the app does not depend directly on platform storage.
Why use a repository?
A repository is a class that hides where and how data is stored. Instead of passing storage calls through widgets, controllers, and API clients, the application uses methods such as saveRefreshToken and readRefreshToken.
This boundary gives you one place to:
- Define storage key names.
- Decide how missing or unreadable data is handled.
- Change storage settings later.
- Replace the real storage with a test double.
- Keep platform details out of authentication code.
The repository should store only the data it owns. If another feature needs a setting or a different credential, give that feature its own key and repository method.
Implementing the repository
Keep the key private to the repository. Callers should not need to know that the value is stored under refresh_token.
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class TokenRepository {
TokenRepository([FlutterSecureStorage? storage])
: _storage = storage ?? const FlutterSecureStorage();
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
Future<void> saveRefreshToken(String token) {
if (token.isEmpty) {
throw ArgumentError.value(token, 'token', 'Cannot be empty');
}
return _storage.write(key: _refreshKey, value: token);
}
Future<String?> readRefreshToken() async {
try {
return await _storage.read(key: _refreshKey);
} on PlatformException {
// The value may be unreadable after a restore or platform change.
await _storage.delete(key: _refreshKey);
return null;
}
}
Future<void> clear() {
return _storage.delete(key: _refreshKey);
}
}
Future<void> restoreSession(TokenRepository tokens) async {
final refreshToken = await tokens.readRefreshToken();
if (refreshToken == null) {
print('No saved session');
return;
}
print('Refresh the session with the saved token');
}The optional constructor parameter enables dependency injection. Dependency injection means giving a class the objects it needs instead of constructing every dependency inside the class. Production code uses the default FlutterSecureStorage; tests can provide a controlled instance.
readRefreshToken returns String? because no value is a normal state. The application can interpret null as signed out. It also catches PlatformException, which represents an error reported by the native storage implementation. Clearing only this repository’s key avoids deleting unrelated secrets.
Keep authentication decisions outside storage
The repository reads and writes bytes represented as strings. It should not decide whether a token is expired, whether a user is allowed to sign in, or how to refresh an access token. An authentication service can make those decisions using the repository.
This separation also prevents accidental logging. Do not print token values while debugging, and do not include them in exception messages or analytics events.
Common mistakes
- Exposing the storage key as a public constant and duplicating it throughout the app.
- Returning an empty string to mean “no token.” Use
nullfor a missing value. - Calling
deleteAllduring sign-out when the same storage contains other features’ secrets. - Treating a storage read error as a valid authenticated session.
- Storing large response objects instead of the small token values required to restore a session.
Exercise
Why does TokenRepository accept an optional FlutterSecureStorage in its constructor?
Show answer
It allows production code to use real secure storage while tests inject controlled storage behavior without changing the repository’s public methods.