0
0
Fluttermobile~15 mins

SharedPreferences for key-value in Flutter - Deep Dive

Choose your learning style9 modes available
Overview - SharedPreferences for key-value
What is it?
SharedPreferences is a way to save small pieces of data on a mobile device so your app can remember things even after it is closed. It stores data as key-value pairs, like a list of labels and their matching values. This is useful for saving simple settings or user preferences without needing a full database.
Why it matters
Without SharedPreferences, apps would forget user choices or settings every time they close, making the experience frustrating. It solves the problem of keeping small data safe and easy to access quickly. This helps apps feel personal and responsive to each user.
Where it fits
Before learning SharedPreferences, you should understand basic Flutter app structure and asynchronous programming. After this, you can learn about more complex storage options like databases or cloud syncing.
Mental Model
Core Idea
SharedPreferences stores small pieces of data as labeled values on the device, so apps can quickly save and retrieve user settings or simple info.
Think of it like...
It's like a labeled drawer where you keep sticky notes with reminders. Each note has a label (key) and a message (value). You can quickly find or change a note by its label anytime.
┌───────────────┐
│ SharedPreferences │
├───────────────┤
│ Key: 'theme'  │ → 'dark'
│ Key: 'userId' │ → '12345'
│ Key: 'volume' │ → 0.8
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is SharedPreferences
🤔
Concept: Introduction to the idea of storing simple data persistently on a device.
SharedPreferences is a plugin in Flutter that lets you save data as key-value pairs. This data stays saved even if the app closes or the phone restarts. It is best for small data like user settings, flags, or tokens.
Result
You understand that SharedPreferences is for saving simple, persistent data on the device.
Knowing that SharedPreferences is for small, persistent data helps you choose the right tool for saving app state or preferences.
2
FoundationHow to add SharedPreferences to Flutter
🤔
Concept: Setting up the SharedPreferences plugin in a Flutter project.
To use SharedPreferences, add it to your pubspec.yaml dependencies: shared_preferences: ^2.0. Then run flutter pub get. Import it in your Dart file with import 'package:shared_preferences/shared_preferences.dart';
Result
Your Flutter app is ready to use SharedPreferences methods.
Setting up the plugin correctly is the first step to accessing device storage for key-value data.
3
IntermediateSaving data with SharedPreferences
🤔Before reading on: do you think saving data with SharedPreferences is synchronous or asynchronous? Commit to your answer.
Concept: Learn how to save different types of data asynchronously using keys.
Use SharedPreferences.getInstance() to get the preferences object asynchronously. Then use methods like setString(key, value), setInt(key, value), setBool(key, value) to save data. For example: final prefs = await SharedPreferences.getInstance(); await prefs.setString('username', 'Alice');
Result
Data is saved on the device and can be retrieved later by the same key.
Understanding that saving is asynchronous prevents bugs and ensures data is stored before continuing.
4
IntermediateReading data from SharedPreferences
🤔Before reading on: do you think reading data returns null if the key does not exist? Commit to your answer.
Concept: How to retrieve saved values safely and handle missing keys.
After getting the SharedPreferences instance, use getString(key), getInt(key), getBool(key) to read values. If the key is missing, these methods return null. Example: final prefs = await SharedPreferences.getInstance(); String? username = prefs.getString('username');
Result
You can access saved values or know when no value exists for a key.
Knowing that missing keys return null helps you write safe code that checks for data presence.
5
IntermediateRemoving and clearing SharedPreferences data
🤔
Concept: Learn how to delete specific keys or clear all saved data.
Use prefs.remove(key) to delete one key-value pair. Use prefs.clear() to remove all stored data. Both are asynchronous. Example: await prefs.remove('username'); await prefs.clear();
Result
You can manage stored data by deleting or resetting it as needed.
Knowing how to remove data helps maintain app state and user privacy.
6
AdvancedHandling data types and limitations
🤔Before reading on: do you think SharedPreferences can store complex objects like lists or maps directly? Commit to your answer.
Concept: Understand what data types SharedPreferences supports and how to work around limitations.
SharedPreferences supports only simple types: int, double, bool, String, and List. To save complex objects, convert them to JSON strings first. For example, encode a map to JSON string and save it as a String. Decode it back when reading.
Result
You can store complex data by converting it, extending SharedPreferences usefulness.
Knowing data type limits prevents errors and guides you to use serialization for complex data.
7
ExpertPerformance and best practices in SharedPreferences
🤔Before reading on: do you think calling SharedPreferences.getInstance() multiple times creates multiple storage copies? Commit to your answer.
Concept: Learn about internal caching, performance tips, and common pitfalls in production apps.
SharedPreferences.getInstance() returns a singleton instance cached internally, so calling it multiple times is cheap. However, frequent writes can slow the app, so batch updates or debounce saves when possible. Avoid storing large data or sensitive info here; use secure storage or databases instead.
Result
You write efficient, safe code using SharedPreferences in real apps.
Understanding internal caching and limits helps you avoid performance issues and security risks.
Under the Hood
SharedPreferences stores data in a platform-specific way: on Android, it uses XML files in app storage; on iOS, it uses NSUserDefaults. The Flutter plugin provides a unified Dart API that calls native code asynchronously to read/write these files. Data is cached in memory for quick access, and writes update the persistent storage.
Why designed this way?
This design allows Flutter apps to use native, optimized storage on each platform without reinventing storage. It balances simplicity, speed, and persistence for small data. Alternatives like databases are heavier and slower for simple key-value needs.
Flutter App
   │
   ▼
SharedPreferences Plugin
   │
   ▼
┌───────────────┐       ┌───────────────┐
│ Android XML   │       │ iOS NSUserDef │
│ (SharedPrefs) │       │ (UserDefaults)│
└───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does SharedPreferences store data instantly and synchronously? Commit to yes or no.
Common Belief:SharedPreferences saves data immediately and synchronously when you call set methods.
Tap to reveal reality
Reality:Saving data is asynchronous and may take time to write to disk; the set methods return Futures you should await.
Why it matters:Ignoring async behavior can cause data loss or race conditions if the app closes before saving finishes.
Quick: Can SharedPreferences store large files or images? Commit to yes or no.
Common Belief:SharedPreferences can store any kind of data, including large files or images.
Tap to reveal reality
Reality:SharedPreferences is only for small key-value data; large files or images should be stored in file storage or databases.
Why it matters:Misusing SharedPreferences for large data can cause app crashes or slow performance.
Quick: If you remove a key from SharedPreferences, does it delete the entire storage? Commit to yes or no.
Common Belief:Removing one key deletes all stored data.
Tap to reveal reality
Reality:Removing a key deletes only that key-value pair; other data remains intact.
Why it matters:Misunderstanding this can lead to accidental data loss or improper data management.
Quick: Does SharedPreferences encrypt stored data by default? Commit to yes or no.
Common Belief:SharedPreferences automatically encrypts data for security.
Tap to reveal reality
Reality:SharedPreferences does not encrypt data; it is stored in plain text and can be accessed if the device is compromised.
Why it matters:Storing sensitive data without encryption risks user privacy and security breaches.
Expert Zone
1
SharedPreferences caches data in memory, so frequent reads are fast, but writes still hit disk asynchronously.
2
The plugin uses platform channels to communicate with native code, which means understanding native storage helps debug issues.
3
Data stored is not encrypted; for sensitive info, combine SharedPreferences with encryption libraries or use secure storage plugins.
When NOT to use
Avoid SharedPreferences for large or complex data, sensitive information, or data requiring relational queries. Use databases like SQLite or secure storage solutions instead.
Production Patterns
In production, SharedPreferences is commonly used for feature flags, user theme preferences, onboarding completion flags, and caching small tokens. Developers batch writes and handle async carefully to avoid data loss.
Connections
Local Database (SQLite)
Builds-on
Understanding SharedPreferences helps grasp why databases are needed for complex or large data storage beyond simple key-value pairs.
Asynchronous Programming
Same pattern
SharedPreferences operations are asynchronous, so mastering async/await in Dart is essential to use it correctly and avoid bugs.
Human Memory and Notes
Analogy
Knowing how humans use labeled notes to remember small facts helps understand why key-value storage is simple yet powerful for apps.
Common Pitfalls
#1Saving data without awaiting the async call.
Wrong approach:final prefs = SharedPreferences.getInstance(); prefs.setString('key', 'value'); // missing await
Correct approach:final prefs = await SharedPreferences.getInstance(); await prefs.setString('key', 'value');
Root cause:Not understanding that getInstance() and set methods return Futures that must be awaited to complete.
#2Trying to store complex objects directly.
Wrong approach:await prefs.setString('user', User(name: 'Alice').toString()); // storing object as string without serialization
Correct approach:String userJson = jsonEncode({'name': 'Alice'}); await prefs.setString('user', userJson);
Root cause:Misunderstanding that SharedPreferences only supports simple data types, requiring manual serialization.
#3Assuming data is encrypted and safe.
Wrong approach:// Storing password directly await prefs.setString('password', 'mypassword123');
Correct approach:// Use secure storage plugin or encrypt before saving String encrypted = encrypt('mypassword123'); await prefs.setString('password', encrypted);
Root cause:Believing SharedPreferences provides security by default, ignoring data privacy best practices.
Key Takeaways
SharedPreferences is a simple way to save small pieces of data persistently on a device using key-value pairs.
All SharedPreferences operations are asynchronous and must be awaited to ensure data is saved or loaded correctly.
It supports only basic data types; complex data must be converted to strings using serialization like JSON.
SharedPreferences is not secure storage; sensitive data should be encrypted or stored using specialized plugins.
Understanding SharedPreferences helps decide when to use simple storage versus databases or secure storage in app development.