Sub topic 5
Writing, reading and deleting values
This chapter covers the core flutter_secure_storage API: write, read, readAll, delete and deleteAll. It assumes you can write Dart with async/await, you have a Flutter app that builds for Android or iOS, and you know how to add a package with pub. It also assumes you have read the earlier chapters on what belongs in secure storage and how the iOS and Android backends work.
Add the package
Add the package from the root of your Flutter project.
flutter pub add flutter_secure_storageThis adds the package to pubspec.yaml at its latest compatible version. Check the package README for the minimum Android SDK version and any iOS or macOS setup it requires. Those requirements change between releases.
The mental model
Secure storage is a persistent key-value store with these properties:
- Keys are strings.
- Values are strings.
- Every call is asynchronous and returns a
Future, because each call crosses a platform channel to native code. - Data survives app restarts. Whether it survives reinstalls depends on the platform (a later chapter covers this).
- A missing key is not an error.
readreturnsnull.
You create a FlutterSecureStorage object and call methods on it. The object holds configuration only, so a single const instance is enough for the whole app.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage();The data lives in the native store (Keychain on iOS, Keystore-backed storage on Android), not in the Dart object. Two instances with the same options see the same data.
The five core operations
The following example uses all of them in sequence.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage();
Future<void> demo() async {
await storage.write(key: 'refresh_token', value: 'abc123');
final token = await storage.read(key: 'refresh_token');
print(token); // abc123
final all = await storage.readAll();
print(all.keys);
await storage.delete(key: 'refresh_token');
print(await storage.read(key: 'refresh_token')); // null
await storage.deleteAll();
}The table summarizes each method.
| Method | Returns | Behavior |
|---|---|---|
| `write(key:, value:)` | `Future<void>` | Stores the value. Overwrites any existing value for the key. |
| `read(key:)` | `Future<String?>` | Returns the value, or `null` if the key does not exist. |
| `readAll()` | `Future<Map<String, String>>` | Returns every key-value pair this app stored. |
| `delete(key:)` | `Future<void>` | Removes one key. Deleting a missing key is not an error. |
| `deleteAll()` | `Future<void>` | Removes every key this app stored. |
Two further methods are worth knowing: containsKey(key:) returns a Future<bool>, and isCupertinoProtectedDataAvailable() is relevant on iOS when data protection may be active. In most apps you will not need them.
Writing
write is an upsert. Calling it twice with the same key replaces the value, and no error is raised.
await storage.write(key: 'api_key', value: 'first');
await storage.write(key: 'api_key', value: 'second');
print(await storage.read(key: 'api_key')); // secondWriting null as the value deletes the key in current versions of the package. Do not rely on this, though. If you mean to delete, call delete, which says so in the code.
Reading
read returns String?, and your code must handle null. Common reasons for null:
- The user has never signed in on this install.
- You deleted the key on sign-out.
- The app was reinstalled and the platform did not keep the data.
Treat null as "no value", not as a failure. Treating it as a failure produces confusing sign-in loops.
Future<bool> hasSession() async {
final token = await storage.read(key: 'refresh_token');
return token != null && token.isNotEmpty;
}Reading everything
readAll returns a Map<String, String>. It is useful for debugging and for migrations. It is rarely right for production logic, because it decrypts and loads every secret into memory at once. Prefer reading the specific key you need.
Avoid printing the values from readAll in logs. Printing the keys, as the example does, is fine.
Deleting
delete removes one key and deleteAll removes all keys that your app stored through this package. Neither throws when there is nothing to remove.
Be careful with deleteAll. If other code in your app stores unrelated values in the same storage, deleteAll removes them too. This is one reason to keep key names and storage access in one place, which a later chapter does with a repository.
Strings only
Values must be strings. To store other data, convert it first. Booleans and numbers need parsing on the way out.
import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage();
Future<void> saveSession({
required String accessToken,
required DateTime expiresAt,
}) async {
final json = jsonEncode({
'access_token': accessToken,
'expires_at': expiresAt.toUtc().toIso8601String(),
});
await storage.write(key: 'session', value: json);
}
Future<Map<String, dynamic>?> loadSession() async {
final raw = await storage.read(key: 'session');
if (raw == null) return null;
return jsonDecode(raw) as Map<String, dynamic>;
}Storing several fields as one JSON value makes the write atomic from your app's point of view. With separate keys, a crash between two writes can leave a token without its expiry. The cost is that you must handle malformed JSON when decoding. If jsonDecode throws a FormatException, treat the session as missing.
Keep values small. Secure storage is meant for tokens, keys and similar short secrets. Large blobs are slow, and some backends have size limits. Store large data in an encrypted database and keep only its key in secure storage.
Sequence of a read
Each call is a round trip from Dart to native code and back. The diagram shows what happens during a read on a device.
Because the call crosses a channel, it takes longer than reading a Dart variable. It is still fast enough for startup checks, but avoid calling it inside build methods or in tight loops. Read once, then keep the value in memory for as long as the screen or session needs it.
Common mistakes
Forgetting to await
Every method returns a Future. If you forget await, the next line may run before the write finishes.
// Bug: the read may run before the write completes.
storage.write(key: 'token', value: 'abc');
final token = await storage.read(key: 'token');Add await to the write. The Dart analyzer lint unawaited_futures helps catch this.
Using the wrong key
Key names are plain strings, so a typo gives you null rather than a compile error. Define keys as constants.
abstract final class StorageKeys {
static const refreshToken = 'refresh_token';
static const accessToken = 'access_token';
}Initializing storage inside a widget
Storage has no connection to open or close. You do not need to create it in initState or dispose of it. A top-level const or an instance passed in by dependency injection is enough.
Assuming read always works
Reads can throw a PlatformException when the native store cannot decrypt the data, for example after a restored backup or a changed device lock setting. Treat this as a separate case from null. The error handling chapter covers it.
Logging secrets
Do not print tokens, even during debugging. Logs can end up in crash reports and on other developers' machines.
Choosing keys
A few conventions keep storage manageable over time:
- Use short, stable, lowercase names with underscores, such as
refresh_token. - Keep all key names in one file.
- When data is per-user, include the user ID in the key, for example
refresh_token_$userId. Then signing out one account does not touch another. - Never put secret data in the key. Keys may be less protected than values on some platforms.
- Version the format of structured values, for example a
"v": 1field in JSON, so you can migrate later.
Quick check of your understanding
Exercise
A user signs in, and your code runs await storage.write(key: 'refresh_token', value: token). On the next launch, await storage.read(key: 'refresh_token') returns null. Name two causes that are not bugs in your read call, and say how the app should respond to null.
Show answer
Possible causes: the user signed out and the key was deleted, or the app was reinstalled and the platform did not keep the data. A null result means "no stored value", so the app should treat the user as signed out and show the sign-in screen. It should not show an error or retry in a loop.
Exercise
You store an access token and its expiry time. Why might you write them as one JSON string under a single key instead of two separate keys, and what must you handle when reading?
Show answer
One write is applied as a unit from your app's point of view, so a crash cannot leave a token saved without its expiry. When reading, you must handle a missing value (null) and malformed JSON (FormatException), and treat both as no session.
Exercise
What is the risk of calling deleteAll() on sign-out in an app where other features also use FlutterSecureStorage?
Show answer
deleteAll removes every key the app stored through the package, including values that belong to unrelated features, such as a database encryption key. On sign-out, delete only the keys that belong to the session, for example by calling delete on each of them.