What are Shared Preferences?
Shared Preferences is a lightweight data storage solution in Flutter, ideal for saving small pieces of data like user settings, login states, or simple preferences. It leverages key-value pairs to store data persistently on a device.
This is a mechanism that allows you to store and retrieve simple data on a device. This data is stored in key-value pairs and is persisted across app sessions. It is best suited for small, non-complex data such as:
- User preferences (e.g., dark mode, language settings)
- Session tokens
- Simple flags (e.g., first-time app usage indicators)
Key Features of Shared Preferences
Lightweight
Best for storing simple key-value data; not suitable for large datasets or complex relationships.
Persistent
Data remains saved even if the app is closed or restarted.
Asynchronous API
Allows reading and writing data without blocking the UI thread.
Adding Shared Preferences to Your Flutter Project
To use Shared Preferences, add the shared_preferences package to your pubspec.yaml file:
Then run:
Using Shared Preferences
Here is a step-by-step guide to using Shared Preferences in your Flutter app.
1. Import the Package
2. Saving Data
To save data, you need to use the set methods provided by SharedPreferences:
3. Retrieving Data
To retrieve data, use the corresponding get methods:
4. Removing Data
To remove a specific key or clear all stored data:
Example: Persisting a Dark Mode Preference
Let’s walk through an example where we save and retrieve a user’s preference for dark mode.
Full Code Example
In this example:
- Dark Mode Preference: Stored using Shared Preferences.
- State Management: The app’s theme toggles based on the saved preference.
When to Use Shared Preferences
Shared Preferences is great for small, simple data. However, it’s not suitable for:
Complex data
For large datasets, use a local database like sqflite or Hive.
Sensitive data
For highly sensitive information, consider using secure storage solutions such as the flutter_secure_storage package.
Final Thoughts
Shared Preferences is an easy and efficient way to persist small amounts of data in Flutter apps. It integrates seamlessly with most applications, making it an excellent choice for storing simple user preferences and states. You can use it to enhance user experience and maintain app states easily!
Enhance Your Flutter Skills
Stay tuned to our blog for more insights on Flutter development.