Sub topic 8
Handling Platform Errors
Assume you know basic Dart async/await, Flutter packages, and authentication tokens. You should also understand the basic read, write, and delete methods of flutter_secure_storage.
A secure-storage call crosses the Flutter platform channel. Dart code sends a request to native iOS or Android code, which then talks to the Keychain or Android secure storage. Any part of that path can fail. The requested key can be missing, but the device can also reject access or return data that is no longer readable.
A missing value is not always an error
read returns null when the key does not exist. This is a normal result, so handle it as an unauthenticated state rather than throwing an exception.
A PlatformException means that native platform code reported a failure. Common causes include:
- A Keychain item cannot be decoded.
- Android encrypted data is invalid after a restore.
- The app's signing identity or platform configuration changed.
- The plugin is unavailable on the current platform.
- The device's secure-storage service is temporarily unavailable.
Do not print the token or include it in an exception message. Secrets can remain in logs long after a failure has been fixed.
flowchart TD
A[Request stored token] --> B{Native read succeeds?}
B -->|Yes| C{Value exists?}
C -->|Yes| D[Continue authenticated]
C -->|No| E[Continue signed out]
B -->|No| F[Catch PlatformException]
F --> G[Clear unusable local state]
G --> ECatch the platform boundary
Catch PlatformException close to the storage call. This keeps platform details inside the data-access layer and lets the rest of the app work with a simple result.
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) {
return _storage.write(key: _refreshKey, value: token);
}
Future<String?> readRefreshToken() async {
try {
return await _storage.read(key: _refreshKey);
} on PlatformException {
// The stored value may be unreadable after a restored backup.
await _storage.deleteAll();
return null;
}
}
Future<void> clear() {
return _storage.delete(key: _refreshKey);
}
}This example treats an unreadable token as signed out. Clearing local secure data prevents the app from repeatedly trying to use corrupted credentials.
deleteAll is appropriate only when this storage instance owns all stored keys. If several features share the same storage, delete only the affected key or use separate repositories and key namespaces.
Do not catch every exception
A broad catch (error) can hide programming errors, such as passing an invalid key or accidentally calling the wrong method. Catch the failures you can handle. Let unexpected errors reach your application's error reporting system.
If cleanup can also fail, decide how the application should behave. The safest authentication behavior is usually to stop treating the user as signed in, even when local cleanup did not complete. You can report the cleanup failure without recording the secret itself.
| Result | Meaning | Typical action |
|---|---|---|
| `String` | A token was read | Validate it and continue |
| `null` | No token is stored | Show signed-out state |
| `PlatformException` | Native storage failed | Clear or isolate stale state |
| Other exception | Unexpected programming or runtime failure | Report and investigate |
> callout warning > Never use secure storage as proof that a user is authenticated. The server must validate access or refresh tokens. Local storage only preserves credentials between app launches.
Testing the failure policy
Mock values test the normal path without a device:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('returns the stored token', () async {
FlutterSecureStorage.setMockInitialValues(
{'refresh_token': 'abc123'},
);
const storage = FlutterSecureStorage();
expect(await storage.read(key: 'refresh_token'), 'abc123');
});
test('returns null for a missing token', () async {
FlutterSecureStorage.setMockInitialValues({});
const storage = FlutterSecureStorage();
expect(await storage.read(key: 'refresh_token'), isNull);
});
}Mock values do not reproduce every native failure. Test the repository's exception branch with an injected fake or a platform-channel test, then verify that the app enters the signed-out state and does not log the token.
Exercise
What should a repository return when read returns null, and what should it do after a PlatformException indicates that the token cannot be decoded?
Show answer
It should treat null as a normal signed-out result. For an unreadable token, it should stop using the credentials, clear the affected local state when safe, and return or report a signed-out result without logging the secret.