Sub topic 8
Handling platform errors
This chapter assumes you can write Dart async/await code and catch exceptions. It also assumes you have a TokenRepository like the one in the previous chapter, wrapping FlutterSecureStorage. Here you will learn which failures the package can raise, how to tell a transient failure from a permanent one, and how to turn each into a predictable app state.
Where errors come from
flutter_secure_storage is a thin Dart layer over native code. Each call crosses a platform channel to the iOS Keychain or to Android's Keystore-backed storage. When the native side fails, the Dart call completes with a PlatformException. The exception has three fields you can inspect:
code: a short identifier set by the native code. Its value is not stable across platforms or package versions.message: a human-readable description, often the text of the underlying native error.details: extra data, sometimes a native error string, sometimesnull.
Two things are not errors:
- Reading a key that does not exist returns
null. - Deleting a key that does not exist completes normally.
Treat null as "nothing stored" and a PlatformException as "the storage itself misbehaved". Mixing these up is the most common bug. Code that treats every exception as "signed out" hides real problems, and code that treats null as a crash breaks first launch.
Common failure modes
The same call can fail for very different reasons. The table lists the cases you are most likely to meet.
| Situation | Platform | Typical symptom | Nature |
|---|---|---|---|
| Data encrypted with a key that no longer exists, for example after restoring a backup onto a new device | Android | `PlatformException` mentioning `BadPaddingException`, `BAD_DECRYPT` or an invalid key | Permanent for that data |
| Keystore temporarily unavailable, for example right after boot or on some vendor builds | Android | `PlatformException` from the Keystore layer | Often transient |
| Item needs an unlocked device but the app runs in the background | iOS | Keychain error such as `errSecInteractionNotAllowed` (-25308) | Transient |
| Missing Keychain entitlement or unsigned build | macOS, some simulators | Keychain error such as -34018 | Configuration problem |
| Browser blocks storage or WebCrypto is unavailable | Web | Exception on read or write | Environment problem |
Exact messages vary between package versions and OS releases. Treat the strings in this chapter as examples to verify on your own devices, and do not rely on them as a contract.
Decision flow
When a call throws, you must choose one of three responses: retry, discard the stored data, or surface the problem. The choice depends on whether the failure is likely to go away.
The important asymmetry is deletion. Deleting is irreversible, and a wrongly deleted refresh token signs the user out. Only delete when you are fairly sure the data can never be read again. For a transient failure, such as a locked Keychain, deleting makes things worse, because the data would have been readable a moment later.
Writing a defensive repository
The earlier version of TokenRepository called deleteAll() on any PlatformException. That is safe for corrupt data but harmful for transient errors. The version below separates the two cases.
import 'dart:developer' as developer;
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Heuristic: does this error mean the stored bytes can never be decrypted?
bool looksLikeCorruptData(PlatformException e) {
final text = '${e.code} ${e.message} ${e.details}'.toLowerCase();
return text.contains('badpadding') ||
text.contains('bad_decrypt') ||
text.contains('invalidkey');
}
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 _readWithOneRetry();
} on PlatformException catch (e, stack) {
developer.log(
'Secure storage read failed',
error: e,
stackTrace: stack,
name: 'TokenRepository',
);
if (looksLikeCorruptData(e)) {
await _storage.deleteAll();
}
return null;
}
}
Future<String?> _readWithOneRetry() async {
try {
return await _storage.read(key: _refreshKey);
} on PlatformException catch (e) {
if (looksLikeCorruptData(e)) rethrow;
await Future<void>.delayed(const Duration(milliseconds: 300));
return _storage.read(key: _refreshKey);
}
}
Future<void> clear() => _storage.delete(key: _refreshKey);
}Three design choices are worth noting.
- Corrupt data is never retried. A retry cannot fix a missing key, so the code rethrows immediately and the outer handler wipes the storage.
- A transient failure gets one retry, then falls back to
null. The user sees the sign-in screen. The stored token is untouched, so the next launch may succeed. - Every failure is logged. Without the log, a Keystore problem looks identical to a user who simply never signed in.
The rethrow inside _readWithOneRetry is deliberate. The corrupt-data check happens in two places, but each place has a different job. The inner one decides whether a retry is worthwhile, and the outer one decides whether to wipe.
Errors on write
Reads fail more often in the field, but writes can fail too, and a failed write is easy to miss. If saveRefreshToken throws after a successful login, the app works until the next restart and then asks the user to sign in again.
Decide what the caller should do. For a login flow, a reasonable policy is:
- Let the exception propagate out of
saveRefreshToken. - In the login controller, catch it, keep the in-memory session alive, and show a non-blocking message such as "Sign-in will not be remembered on this device".
Do not swallow write errors silently inside the repository. The repository does not know whether losing persistence matters to the screen that called it.
import 'package:flutter/services.dart';
Future<void> completeLogin(
TokenRepository tokens,
String refreshToken,
void Function(String message) showNotice,
) async {
try {
await tokens.saveRefreshToken(refreshToken);
} on PlatformException {
showNotice('Sign-in will not be remembered on this device.');
}
}Pitfalls
Other mistakes to avoid:
- Catching
Exceptionor using a barecatch. This also catches programming errors such as aTypeError, and they then look like storage failures. CatchPlatformExceptionspecifically. - Reading storage in
main()before the first frame without a guard. An unhandled exception there leaves the user on a blank screen. Wrap the call as shown above and decide on a fallback state first. - Calling
deleteAll()when the storage holds other apps' data.deleteAll()removes every value written through this package in your app, not only the token. If you also keep a database encryption key there, wiping it makes your local database unreadable. Usedelete(key:)for single keys when the failure is limited to one of them. For a decryption failure, which usually affects all values,deleteAll()is the correct choice. - Assuming iOS and Android fail the same way. The simulator or emulator often hides problems that appear only on real devices, such as background reads while the phone is locked.
Testing the error paths
setMockInitialValues can only supply values. It cannot make a read throw. To test the error paths, replace the whole storage object with a mock. The example uses the mocktail package, which you add as a dev dependency with flutter pub add --dev mocktail.
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:your_app/token_repository.dart'; // adjust to your package name
class MockStorage extends Mock implements FlutterSecureStorage {}
void main() {
late MockStorage storage;
late TokenRepository repo;
setUp(() {
storage = MockStorage();
repo = TokenRepository(storage);
});
test('wipes storage and returns null on undecryptable data', () async {
when(() => storage.read(key: 'refresh_token')).thenThrow(
PlatformException(code: 'Exception', message: 'BadPaddingException'),
);
when(() => storage.deleteAll()).thenAnswer((_) async {});
expect(await repo.readRefreshToken(), isNull);
verify(() => storage.deleteAll()).called(1);
});
test('keeps data and returns null after a transient failure', () async {
when(() => storage.read(key: 'refresh_token')).thenThrow(
PlatformException(code: '-25308', message: 'interaction not allowed'),
);
expect(await repo.readRefreshToken(), isNull);
verifyNever(() => storage.deleteAll());
verify(() => storage.read(key: 'refresh_token')).called(2);
});
}The second test checks the retry. The mock throws on both attempts, so read runs twice and deleteAll never runs. Together the two tests pin down the rule that only corrupt data is wiped.
Summary of the policy
nullfromreadmeans no value. APlatformExceptionmeans the storage failed.- Wipe only when the data is permanently unreadable.
- Retry once for anything else, then fall back to a signed-out state without deleting.
- Log every failure with its stack trace.
- Let write failures reach the caller, which knows how to inform the user.
- Test each path with a mocked storage.
Exercise
A background task in your app reads the refresh token while the phone is locked. The read throws a PlatformException with Keychain code -25308. Your handler calls deleteAll() for every PlatformException. What goes wrong, and how would you change the handler?
Show answer
The error is transient: the Keychain item needs an unlocked device, but the data is intact. Calling deleteAll() destroys a valid token, so the user is signed out for no reason once they unlock the phone. Change the handler to wipe only when the error looks like undecryptable data (for example BadPaddingException on Android). For other errors, retry once, log the failure, and return null without deleting. Also consider setting the iOS accessibility to first_unlock so background reads succeed.
Exercise
Why can't FlutterSecureStorage.setMockInitialValues be used to test that your repository wipes storage on a decryption error, and what should you use instead?
Show answer
setMockInitialValues only fills an in-memory map with values that reads return successfully, so it cannot make a call throw. Inject a mock FlutterSecureStorage (for example with mocktail) whose read throws a PlatformException, then verify that deleteAll was called.