Learn/Local Storage/SharedPreferences

SharedPreferences

Store simple key-value data persistently on the device

6 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. SharedPreferences Data Design
  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. 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

SharedPreferences

SharedPreferences stores small key-value pairs persistently on the device. It is the simplest form of local storage in Flutter and is perfect for saving user settings, preferences, and small pieces of data like the chosen theme, whether the user has completed onboarding, or the last selected language. The data survives app restarts because it is written to a file on disk. However, it is not encrypted and should never be used for sensitive information like passwords or tokens.

dart
1// Add to pubspec.yaml: shared_preferences: ^2.2.0
2import 'package:shared_preferences/shared_preferences.dart';
3
4// ── Save Data ──
5Future<void> saveSettings() async {
6 final prefs = await SharedPreferences.getInstance();
7
8 await prefs.setString('username', 'FlutterDev');
9 await prefs.setBool('darkMode', true);
10 await prefs.setInt('loginCount', 5);
11 await prefs.setDouble('fontSize', 16.0);
12 await prefs.setStringList('favorites', ['item1', 'item2']);
13}
14
15// ── Read Data ──
16Future<void> loadSettings() async {
17 final prefs = await SharedPreferences.getInstance();
18
19 final username = prefs.getString('username') ?? 'Guest';
20 final darkMode = prefs.getBool('darkMode') ?? false;
21 final loginCount = prefs.getInt('loginCount') ?? 0;
22 final fontSize = prefs.getDouble('fontSize') ?? 14.0;
23 final favorites = prefs.getStringList('favorites') ?? [];
24}
25
26// ── Remove Data ──
27Future<void> clearData() async {
28 final prefs = await SharedPreferences.getInstance();
29 await prefs.remove('username'); // remove one key
30 await prefs.clear(); // remove everything
31}

When to Use SharedPreferences

💡 When to Use SharedPreferences

Use SharedPreferences for small, simple data like settings. For structured data, lists of objects, or large datasets, use Hive or SQLite instead.

SharedPreferences Data Design

Treat SharedPreferences keys as a public contract in your app. Decide naming and defaults up front:

  • Group keys by feature, for example settings.themeMode and onboarding.completed.
  • Always read with default values so first launch behaves predictably.
  • Keep write logic in one service class to avoid scattered key names.
  • Plan migration paths if you rename keys in later app versions.

This discipline prevents silent bugs where one screen writes a key in one format and another screen reads a different format.

SharedPreferences Pitfalls

  • Saving large JSON blobs that should live in Hive or SQLite instead.
  • Hardcoding the same key name in multiple files and introducing typos.
  • Assuming synchronous reads and causing UI to show stale defaults first.
  • Storing secrets like auth tokens in plain text preferences.
  • Forgetting to handle key migrations after app updates.

SharedPreferences Release Checklist

  • All preference keys are centralized and documented in one place.
  • Cold start restores expected settings without flicker.
  • Clearing one key does not accidentally wipe unrelated preferences.
  • App behavior is correct when keys are missing or corrupted.
  • No sensitive data is stored in plain text preferences.

This Lesson In Simple Words

Store simple key value data persistently on the device. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

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

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What types of data can SharedPreferences store?".

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

Connect this lesson to separation of concerns so your codebase stays maintainable as it grows.

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 "SharedPreferences" 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: Moving forward without checking whether the current concept is truly clear.
  • 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 types of data can SharedPreferences store?

SharedPreferences supports 5 types: String, bool, int, double, and List<String>.

How do you get an instance of SharedPreferences?

SharedPreferences.getInstance() is an async factory that returns the singleton instance.

What happens if you read a key that does not exist?

Non-existent keys return null, which is why the ?? operator is used to provide defaults.

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