Module 3
Topic 1

SharedPreferences

Storing simple key-value pairs persistently in Flutter — the easiest way to save user preferences and app settings.

shared_preferences package
What Is SharedPreferences?

SharedPreferences is a Flutter plugin that provides a simple way to store key-value pairs persistently across app sessions. It wraps platform-specific persistent storage:

🤖
Android
SharedPreferences
🍎
iOS/macOS
NSUserDefaults
🌐
Web
LocalStorage

✅ When to Use SharedPreferences

  • Storing user preferences (theme, language, notifications)
  • Saving app settings (sound, volume, font size)
  • Storing simple user data (username, email, high score)
  • Session data (login state, last visit)

⚠️ Not for Large Data

SharedPreferences is designed for small amounts of simple data . Do not use it for storing large lists, images, or complex objects. For large data, use Hive or SQLite .

Supported Data Types

SharedPreferences supports the following data types:

📦 Primitive Types

  • int – Integer values
  • double – Decimal values
  • bool – True/false values
  • String – Text values

📋 Collection Types

  • List<String> – Lists of strings

Note: For lists of other types, use JSON serialization.

Setup and Usage

To use SharedPreferences, you need to add the dependency and import the package.

Complete Example: Settings App

Here's a complete example of a settings app that uses SharedPreferences to persist user preferences.

Step-by-Step Explanation
1.
Add the dependency – Add shared_preferences: ^2.5.5 to your pubspec.yaml .
2.
Get an instance – Call SharedPreferences.getInstance() to get a reference to the preferences.
3.
Write data – Use setXxx() methods to store data (e.g., setBool('key', value) ).
4.
Read data – Use getXxx() methods to retrieve data with fallback values.
5.
Delete data – Use remove('key') to delete a single key or clear() to delete all.
Best Practices

✅ Do's

  • Use meaningful key names (e.g., 'user_theme_preference' )
  • Always provide fallback values when reading ( ?? defaultValue )
  • Group related preferences with consistent prefixes
  • Consider using a service class to encapsulate all SharedPreferences logic
  • Call reload() if preferences are modified outside the app

❌ Don'ts

  • Don't store large objects or large lists
  • Don't store sensitive data (use encryption for passwords)
  • Don't use SharedPreferences for critical data (writes are asynchronous)
  • Don't use SharedPreferences as a database for large datasets
Common Mistakes
❌ Mistake 1: Forgetting to await

SharedPreferences.getInstance() and all setXxx() methods are asynchronous. Always use await or handle the Future properly.

✅ Correct: Always await async methods

final prefs = await SharedPreferences.getInstance();
await prefs.setBool('key', value);

❌ Mistake 2: Not providing fallback values

If a key doesn't exist, getXxx() returns null . Not handling this can cause null errors.

✅ Correct: Always provide fallback values

final bool isDark = prefs.getBool('dark_mode') ?? false;

❌ Mistake 3: Storing complex objects

SharedPreferences doesn't support custom objects. Trying to store them directly will cause errors.

✅ Correct: Use JSON serialization for objects

Convert objects to JSON strings using jsonEncode() and parse with jsonDecode() .

🎯 Key Takeaway

SharedPreferences is the simplest way to store small amounts of key-value data in Flutter. It's perfect for user preferences, app settings, and simple state that needs to persist across app sessions. Always provide fallback values and use a service class to keep your code clean.