Sub topic 6
A token repository around the storage
This chapter assumes you can read basic Dart with async/await, that your Flutter app builds for Android or iOS, and that flutter_secure_storage is already installed. You should also know that an app typically holds a short-lived access token and a longer-lived refresh token. The previous chapter covered write, read, delete and readAll. Here you put those calls behind one class.
Why wrap the storage
You can call FlutterSecureStorage directly from any widget, but that spreads three problems through your code.
- Key strings get duplicated. If one file writes
'refresh_token'and another reads'refreshToken', you get anulland no error. - Error handling gets duplicated or forgotten. Every call site would need its own
try/catch. - Tests need a platform. Code that builds
FlutterSecureStorageinline is harder to test without a device.
A repository is a small class that owns one kind of data and exposes only the operations the rest of the app needs. For tokens, that is "save", "read" and "clear". The rest of the app never learns that a Keychain or a Keystore exists.
The repository
This is the complete class. It is the same code you will extend and test later.
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) =>
_storage.write(key: _refreshKey, value: token);
Future<String?> readRefreshToken() async {
try {
return await _storage.read(key: _refreshKey);
} on PlatformException {
// Stored data may be unreadable, for example after a restored backup.
await _storage.deleteAll();
return null;
}
}
Future<void> clear() => _storage.delete(key: _refreshKey);
}The constructor accepts an optional storage
TokenRepository([FlutterSecureStorage? storage]) takes an optional positional argument. Production code calls TokenRepository() and gets a default FlutterSecureStorage. A test, or a caller that needs custom platform options, passes its own instance. This is plain constructor injection, and it needs no dependency-injection package.
If you configured platform options such as Keychain accessibility, create the configured instance once and pass it in:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const configuredStorage = FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
),
);
final tokens = TokenRepository(configuredStorage);This assumes TokenRepository is imported from where you defined it. Do not create a second, differently configured instance elsewhere. Items written with one accessibility setting may not be found when you read with another, so keep a single configuration point.
The key is private and constant
_refreshKey is static const and private to the file. Nothing outside the class can misspell it or write to it directly. If you later rename the key, you change one line. Renaming also orphans the old value on every installed device, so treat key names as part of your stored data format.
Writes are passed through
saveRefreshToken returns the Future from write without a try/catch. A failed write is a real problem: the user would be signed out on the next launch, and you want to know. Let the exception reach the caller, which can show a message or log it.
Reads treat failure as signed out
readRefreshToken returns String?. A null means "no usable token", and the caller sends the user to the sign-in screen. There are two paths to null:
- The key does not exist.
readreturnsnullon its own. - The platform throws a
PlatformException. The repository clears the storage and returnsnull.
The second path matters on Android, where stored data can become undecryptable. A common cause is an app backup restored onto a new device, where the Keystore key that encrypted the data does not exist. The next chapters cover why. Without the catch, the app would crash or loop on every launch. Treating the failure as signed out gives the user a way back in.
clear deletes one key
clear deletes only the refresh token key. Use it on sign-out.
A caution about deleteAll
deleteAll removes everything this package has stored for your app, not just the token. In the repository above that is acceptable, because the token is the only secret and an unreadable store is already broken. If you later store other secrets, such as a database encryption key, a token read failure would wipe them too.
Two options:
- Keep
deleteAlland accept that any storage failure resets all secrets. This is simple and fails safe. - Replace it with
delete(key: _refreshKey). This keeps other values, but if the failure affects the whole store, other reads will throw as well.
Decide deliberately and write the choice in a comment. Keep one repository per kind of secret only if you are sure the failure modes are independent. On Android they usually are not, because one Keystore problem affects everything.
Extending the repository
A real app often needs the access token too. Short-lived access tokens are often kept in memory only and refreshed from the stored refresh token on launch. That shrinks what you persist. If you do persist both, add a second key and make sign-out clear both.
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SessionTokens {
const SessionTokens({required this.access, required this.refresh});
final String access;
final String refresh;
}
class SessionRepository {
SessionRepository([FlutterSecureStorage? storage])
: _storage = storage ?? const FlutterSecureStorage();
static const _accessKey = 'access_token';
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
Future<void> save(SessionTokens tokens) async {
await _storage.write(key: _accessKey, value: tokens.access);
await _storage.write(key: _refreshKey, value: tokens.refresh);
}
Future<SessionTokens?> read() async {
try {
final access = await _storage.read(key: _accessKey);
final refresh = await _storage.read(key: _refreshKey);
if (access == null || refresh == null) return null;
return SessionTokens(access: access, refresh: refresh);
} on PlatformException {
await _storage.deleteAll();
return null;
}
}
Future<void> clear() async {
await _storage.delete(key: _accessKey);
await _storage.delete(key: _refreshKey);
}
}Two details in this version:
readreturnsnullif either token is missing. A half-written session is not usable, so the code treats it as signed out instead of returning a partial object.savewrites two keys one after the other, and the package gives you no transaction. If the app dies between the writes, you hold a new access token with an old refresh token, or the reverse. The null check on read does not catch this mismatch. If it matters to you, store both tokens as one JSON string under a single key, so onewritestores both or neither.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `read` returns `null` right after a successful `write` | Different key strings, or a different `FlutterSecureStorage` options setup between the write and the read | Keep keys in constants and create one configured instance |
| Crash on launch after restoring a device backup (Android) | The stored data cannot be decrypted | Catch `PlatformException` and clear, as in `readRefreshToken` |
| The user stays signed in after sign-out | `clear` was not called, or only one of several keys was deleted | Route every sign-out through the repository's `clear` |
| Tests fail with `MissingPluginException` | The code under test uses the real platform channel | Use `FlutterSecureStorage.setMockInitialValues` (next chapters) |
| Other secrets vanish after a token read error | `deleteAll` removes every stored key | Delete specific keys, or accept the full reset deliberately |
Using the repository in app code
A typical startup decision looks like this:
Future<bool> isSignedIn(TokenRepository tokens) async {
final refresh = await tokens.readRefreshToken();
return refresh != null && refresh.isNotEmpty;
}Here the function takes the repository as a parameter instead of constructing it. Widgets and services receive the repository from above, through a constructor, a Provider, or whatever state management you already use. That keeps the choice of storage in one place and lets tests supply a repository built on mock values.
The check refresh.isNotEmpty guards against an empty string. The package happily stores '', and read will return it as a non-null value.
What this design gives you
- One place to change key names, options and error policy.
- Call sites that read like the domain:
saveRefreshToken,clear. - Failure behaviour that is defined once: a broken store means signed out, not a crash.
- A constructor that accepts a storage, so tests need no device.
The next chapters build on this class. They cover platform options in more depth, how reinstalls and backups affect stored values, and how to write unit tests against the repository.
Exercise
A teammate changes static const _refreshKey = 'refresh_token'; to 'refreshToken' as a style cleanup. The app builds and its tests pass using fresh mock values. What happens to users who update to the new version, and how would you avoid it?
Show answer
Existing users still have their token under the old key 'refresh_token'. After the update, read looks up 'refreshToken', finds nothing, and returns null, so everyone is signed out once. Tests with fresh mock values do not catch this because they never contain the old key. To avoid it, keep the old key name, or add a one-time migration: read the old key, write its value under the new key, then delete the old key.
Exercise
In SessionRepository.save, the access token is written and then the app is killed before the refresh token is written. Explain why read may still return a mismatched pair, and describe a change that makes the pair consistent.
Show answer
If an earlier session left both keys populated, killing the app between the two writes leaves the new access token next to the old refresh token. read finds both non-null and returns them, so the null check does not detect the mismatch. Store both tokens in one value, for example jsonEncode({'access': ..., 'refresh': ...}) under a single key. A single write then replaces both together, and read decodes the JSON.