Learn/Local Storage/Secure Storage

Secure Storage

Store sensitive data like tokens and passwords securely

5 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Token Lifecycle Plan
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Secure Storage

The flutter_secure_storage package uses each platform's built-in secure storage mechanism to protect sensitive data. On iOS it uses the Keychain, and on Android it uses EncryptedSharedPreferences. This means your data is encrypted at rest by the operating system itself. Use it for any sensitive information your app needs to persist, such as authentication tokens, refresh tokens, API keys, user passwords, or encryption keys. Unlike SharedPreferences which stores everything in plain text, secure storage ensures that even if someone gains access to the device files, they cannot read your stored secrets.

dart
1// pubspec.yaml: flutter_secure_storage: ^9.0.0
2import 'package:flutter_secure_storage/flutter_secure_storage.dart';
3
4final storage = const FlutterSecureStorage();
5
6// ── Write secure data ──
7await storage.write(key: 'auth_token', value: 'eyJhbGciOiJIUz...');
8await storage.write(key: 'refresh_token', value: 'dGhpcyBpcyBh...');
9await storage.write(key: 'pin', value: '1234');
10
11// ── Read secure data ──
12final token = await storage.read(key: 'auth_token');
13if (token != null) {
14 // User is authenticated
15 print('Token: $token');
16}
17
18// ── Delete data ──
19await storage.delete(key: 'auth_token');
20
21// ── Delete ALL secure data ──
22await storage.deleteAll();
23
24// ── Check if key exists ──
25final hasToken = await storage.containsKey(key: 'auth_token');
26
27// ── Read all keys ──
28final allData = await storage.readAll();
29allData.forEach((key, value) => print('$key: $value'));

Never Use SharedPreferences for Secrets

⚠️ Never Use SharedPreferences for Secrets

SharedPreferences stores data in plain text. Always use flutter_secure_storage for tokens, passwords, API keys, and other sensitive data.

Token Lifecycle Plan

Secure storage is one part of auth security, not the whole system. Define lifecycle rules:

  • Store short-lived access tokens and refresh tokens separately.
  • On sign-out, delete all auth-related keys in one atomic flow.
  • If token refresh fails, clear secure storage and force re-authentication.
  • Keep token usage in a dedicated auth service rather than UI widgets.

Strong lifecycle design prevents stale credentials and reduces account takeover risk on shared devices.

Secure Storage Pitfalls

  • Printing tokens in logs during debugging and forgetting to remove logs.
  • Keeping expired tokens forever with no cleanup strategy.
  • Writing secret values under predictable generic key names only.
  • Mixing secure and insecure storage for the same credential set.
  • Skipping null checks and assuming secure keys always exist.

Security Verification Checklist

  • All auth tokens are written to secure storage only.
  • Sign-out reliably clears all credential keys every time.
  • App startup handles missing or invalid token states gracefully.
  • No sensitive value is shown in analytics, logs, or crash reports.
  • Token refresh and forced logout flows are tested on both Android and iOS.

This Lesson In Simple Words

Store sensitive data like tokens and passwords securely. Backend integration connects app actions to real user data and secure business workflows.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Define data model and access rules before writing convenience helper methods.

Deep Understanding Guide

Why this lesson matters

Security and data integrity issues can damage user trust faster than UI bugs.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Think from both sides: client UX and backend authorization constraints.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Trusting client-side checks without enforcing server-side rules.
  • Using broad read/write permissions in Firestore rules.
  • Storing secrets in plain text or unsafe local storage.
  • Not versioning schemas when documents evolve over time.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write one secure Firestore rule and test allow/deny cases.
  • Map one backend document model to a typed client model.
  • Implement auth-state based screen routing with guarded actions.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does flutter_secure_storage use on iOS?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Security rules are part of architecture, not optional deployment polish.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Secure Storage" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Trusting client-side checks without enforcing server-side rules.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does flutter_secure_storage use on iOS?

On iOS, flutter_secure_storage uses the Keychain, which is Apple's secure encrypted storage.

Which is the correct way to read a secure value?

The read() method takes a named parameter key and returns a Future<String?>: null if the key doesn't exist.

What kind of data should you store with flutter_secure_storage?

Secure storage is designed for sensitive data like auth tokens, passwords, and API keys.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue