Flutter Secure Storage | Best Way to Store Data Securely in Android or iOS
In Flutter, Flutter Secure Storage is a popular package for securely storing sensitive data like tokens, passwords, or credentials or other sensitive information. It uses platform-specific solutions like the Android Keystore and iOS Keychain to encrypt data, ensuring it is protected from unauthorized access.
Why Use Flutter Secure Storage?
- Encryption: Data is stored securely with encryption.
- Platform-Specific Safety: Uses Android Keystore and iOS Keychain for safe storage.
- Persistent Storage: Keeps data even when the app is closed or restarted.
- Easy Integration: Provides a simple API for saving, retrieving, and deleting data.
How to Use Flutter Secure Storage
- Add the Package
Add the following dependency in yourpubspec.yaml
file:
dependencies:
flutter_secure_storage: ^9.0.0
- Import the Package
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
- Initialize Secure Storage
Create an instance ofFlutterSecureStorage
:
final storage = FlutterSecureStorage();
- Storing Data Securely
await storage.write(key: 'auth_token', value: 'your_secure_token');
- Retrieving Data
String? token = await storage.read(key: 'auth_token');
if (token != null) {
print('Stored Token: $token');
}
- Deleting Data
await storage.delete(key: 'auth_token');
- Checking All Stored Keys
Map<String, String> allValues = await storage.readAll();
print(allValues);
Best Practices for Secure Data Storage
- Store Minimal Data: Only store what is absolutely necessary (e.g., authentication tokens).
- Use
writeEncrypted
(if needed): For extra encryption within the app. - Clear Data on Logout: Ensure data is deleted when the user logs out to prevent misuse.
- Use Platform-Specific Settings: Adjust
AndroidOptions
orIOSOptions
if needed.
Example with Android and iOS specific options:
final storage = FlutterSecureStorage(
aOptions: AndroidOptions(encryptedSharedPreferences: true),
iOptions: IOSOptions(accessibility: KeychainAccessibility.first_unlock),
);
When to Use Flutter Secure Storage?
- Authentication Tokens: Storing JWT or OAuth tokens for secure access.
- User Credentials: Saving usernames or API keys.
- Preferences: Saving sensitive user settings like biometrics or PIN codes.
Conclusion
Flutter Secure Storage is the best way to store sensitive data securely in Android and iOS apps. It leverages platform encryption, making it a reliable option for tasks like authentication and user credentials storage.
Note: For secure keys or ID like Google Map API key use flutter_dotenv