Sub topic 4
Adding flutter_secure_storage to your app
This chapter takes you from an app with no secure storage to one that writes, reads and deletes a value on a real device. It assumes you can build a Flutter app for Android or iOS, add packages with pub, and read basic async/await code. It also assumes you have read the earlier chapters on what belongs in secure storage and how the iOS and Android backends work. Here we only deal with installation, platform configuration, and a smoke test that proves the setup works.
What the package gives you
flutter_secure_storage is a plugin. Its Dart API is small, and it forwards each call over a platform channel to native code:
- On iOS and macOS, native code uses the Keychain.
- On Android, native code encrypts values with a key held in the Android Keystore and keeps the encrypted data in app-private storage.
- On Linux, Windows and the web, it uses other mechanisms with different guarantees. The last section of this chapter covers them briefly.
Because the plugin has native code, adding it is different from adding a pure Dart package. You must do a full rebuild, not a hot reload. You also need to check the native build settings of each platform you ship.
Step 1: Add the dependency
From the root of your Flutter project, run:
flutter pub add flutter_secure_storageThis adds the latest compatible version to pubspec.yaml and runs flutter pub get. The result looks like this, though your version number will differ:
dependencies:
flutter:
sdk: flutter
flutter_secure_storage: ^9.2.2Commit pubspec.lock if your project is an app. Pinning the resolved version matters here because the package's Android implementation has changed between major versions, and a silent upgrade can change how existing data is read.
Step 2: Configure Android
Android is where most setup failures happen. Check three things.
Minimum SDK version
The package requires a minimum Android API level, and the requirement has risen between releases. Recent versions need API 23 (Android 6.0). Open the Gradle file in android/app and set the minimum accordingly. Flutter's default templates have changed over time, so you will see one of two forms.
If your project uses a Groovy file, android/app/build.gradle:
android {
defaultConfig {
minSdkVersion 23
}
}If it uses a Kotlin script, android/app/build.gradle.kts:
android {
defaultConfig {
minSdk = 23
}
}If you leave the default flutter.minSdkVersion and it is lower than the package needs, the build fails with a manifest merger error that names flutter_secure_storage and its minSdkVersion. The fix is to raise the value. Confirm the current number in the package README, because it is the one fact in this section most likely to change.
Auto Backup
Android can back up app data to the user's Google account and restore it on a new device. The encrypted values may be restored, but the Keystore key that decrypts them is hardware-bound and does not travel with the backup. The restored data is then unreadable, and reads throw errors. The package README describes how to exclude its storage from backups with backup rules in your manifest. A later chapter covers this failure in detail. For now, know that a fresh install that restores a backup is a common cause of "works on my phone, fails after I switched phones" reports.
Build tooling
The plugin is compiled with your app's Android Gradle Plugin and Java settings. If you work on an old project, a plugin version bump can expose an out-of-date Gradle or Kotlin version. Read the error message first. It usually names the setting that is too old.
Step 3: Configure iOS and macOS
On iOS the default configuration works without changes. The Keychain is available to every app, and the plugin uses it with default settings. Two points are still worth knowing:
- Keychain items belong to your app's bundle identifier and signing team. If you change either, the new build cannot read items written by the old one.
- iOS Keychain items can survive an app uninstall and reinstall. That is a lifecycle pitfall, not a setup problem, and it gets its own chapter.
On macOS, the Keychain needs an entitlement. If you target macOS, open the macOS project in Xcode and add the Keychain Sharing capability to the Runner target, for both debug and release configurations. Without it, writes fail with an error such as -34018 ("A required entitlement isn't present"). Alternatively, add the keychain entitlement directly to DebugProfile.entitlements and Release.entitlements. Check the README for the exact key and current guidance.
After changing anything native, stop the app and run a full build. Hot reload and hot restart do not reload native code.
Step 4: Check your setup with a smoke test
Before writing your real repository class, confirm the plugin works on a device. The following app writes a value, reads it back, deletes it, and shows the result on screen. It also catches errors so you can see what the native side reports. Replace lib/main.dart with it:
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
void main() => runApp(const MaterialApp(home: SmokeTestPage()));
class SmokeTestPage extends StatefulWidget {
const SmokeTestPage({super.key});
@override
State<SmokeTestPage> createState() => _SmokeTestPageState();
}
class _SmokeTestPageState extends State<SmokeTestPage> {
static const _storage = FlutterSecureStorage();
static const _key = 'smoke_test';
String _status = 'Not run yet';
Future<void> _run() async {
try {
await _storage.write(key: _key, value: 'hello');
final value = await _storage.read(key: _key);
await _storage.delete(key: _key);
final after = await _storage.read(key: _key);
setState(() {
_status = 'read: $value, after delete: $after';
});
} catch (e) {
setState(() {
_status = 'Error: $e';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Secure storage smoke test')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_status),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _run,
child: const Text('Run test'),
),
],
),
),
);
}
}Run it on a physical device or an emulator:
flutter runTap Run test. A working setup shows read: hello, after delete: null. The second value is null because read returns null for a key that does not exist. It does not throw.
The following diagram summarises the order of the setup steps.
Reading failures
When the smoke test or the build fails, the cause usually falls into one of these groups.
| Symptom | Likely cause | What to do |
|---|---|---|
| Build fails with a manifest merger error mentioning `minSdkVersion` | Android minimum SDK is lower than the plugin requires | Raise `minSdkVersion` or `minSdk` as shown above |
| `MissingPluginException` at runtime | App was hot-reloaded or hot-restarted after the plugin was added, so native code is not registered | Stop the app and run `flutter run` again |
| `PlatformException` with a Keychain error code on macOS | Missing Keychain Sharing entitlement | Add the capability for debug and release |
| `PlatformException` on Android during `read` | Stored data cannot be decrypted, often after a backup restore or an OS or key change | Clear the storage and treat the user as signed out (see the error handling chapter) |
| Works in debug, fails in release | Code shrinking removed classes the plugin needs | Check the README for current ProGuard or R8 rules |
MissingPluginException is the most common first-time error, and it is almost always fixed by a full restart.
Create one instance and choose where it lives
FlutterSecureStorage is a lightweight object. Creating several instances with the same options is safe, because all of them talk to the same native storage. The smoke test used a static const instance for simplicity. In a real app, create the instance in one place, either as a const field in your repository class or injected through your dependency injection setup. Both choices let you pass a different instance in tests. A later chapter builds that repository.
Keep two things consistent across every instance you create:
- Platform options. If one part of the app writes with
IOSOptions(accessibility: ...)and another reads with different options, reads may not find the item. Define the options once and reuse them. - Key names. Keys are plain strings with no compiler checking. A typo in one call silently reads
null. Define key names as constants in one place.
Web and desktop
If your app targets only Android and iOS, you can skip this section. If it targets other platforms, the guarantees are different:
- Linux needs the
libsecretdevelopment packages installed to build, and a running keyring service at run time. Without a keyring, operations fail. - Windows stores encrypted data using the platform's credential facilities. Check the README for build requirements.
- Web encrypts values with the browser's Web Crypto API and stores them in
localStorage. The key is also kept in the browser, so this is obfuscation, not protection against someone who can run script on your page or inspect browser storage. It also requires a secure context (HTTPS, or localhost during development).
Common mistakes at this stage
- Testing only in the debug configuration. Run a release build once before you consider setup finished. Shrinking and signing differences show up only there.
- Skipping the physical device. Emulators and simulators usually work, but Keychain and Keystore behaviour can differ from hardware, especially around lock screen settings.
- Calling storage methods in
main()beforeWidgetsFlutterBinding.ensureInitialized(). Platform channels need the binding. If you read a token beforerunApp, callWidgetsFlutterBinding.ensureInitialized()first. - Storing the instance in a global that tests cannot replace. This blocks the mock approach used in the testing chapter. Pass the storage in through a constructor instead.
Summary of what you now have
- The package is in
pubspec.yaml, andpubspec.lockrecords the exact version. - Android's minimum SDK meets the plugin's requirement, and you know to check Auto Backup behaviour.
- macOS targets have the Keychain entitlement, if you use them.
- A smoke test confirmed that write, read and delete work on a real build.
- You know the error patterns that point to a setup problem, not a code problem.
The next chapters use this working setup to look at the basic operations in more detail and to wrap them in a repository.
Exercise
You add fluttersecurestorage to an existing app, then press hot reload. The first call to storage.read(key: 'token') throws MissingPluginException. Why does this happen, and what do you do? After the fix, the build for an older Android project fails with a manifest merger error that mentions minSdkVersion. What is the cause and the fix?
Show answer
The plugin contains native code, and hot reload and hot restart do not register native plugins that were added after the app launched, so the platform channel has no handler. Stop the app and run flutter run again for a full rebuild. The manifest merger error means the project's Android minimum SDK is lower than the plugin requires. Raise minSdkVersion (Groovy) or minSdk (Kotlin script) in the app-level Gradle file to the value the package README states, currently 23 for recent versions, then rebuild.
Exercise
The smoke test prints read: hello, after delete: null. Which part of that output shows the behaviour of read for a missing key, and why does your later code not need a try/catch just to handle a key that was never written?
Show answer
The null after delete shows it. read returns null for a key that does not exist and does not throw. Code that reads a possibly missing value should handle the null result (for example, treat it as signed out). A try/catch is needed only for platform failures, such as unreadable data, which throw PlatformException.