Flutter SharedPreferences: A Practical Guide
SharedPreferences is the go-to solution for storing small amounts of data in Flutter apps. Whether you need to remember a user's theme preference, save a login token, or track whether onboarding was completed, this plugin offers a straightforward key-value store that persists across app launches.
In this guide, we'll walk through a complete example of using SharedPreferences in a Flutter app. We'll cover initialization, reading and writing values, handling asynchronous operations, and best practices for testing and performance.
Setting Up SharedPreferences
To get started, add the shared_preferences package to your pubspec.yaml file. Run `flutter pub add shared_preferences` or manually add the dependency. This package is maintained by the Flutter team and supports all platforms including iOS, Android, web, and desktop.
After adding the dependency, import it in your Dart file: `import 'package:shared_preferences/shared_preferences.dart';`. You can then obtain an instance by calling `SharedPreferences.getInstance()`, which returns a Future. It's common to initialize this in your main function or in a stateful widget's initState.
For simple apps, you might call getInstance each time you need to read or write. However, for better performance, consider caching the instance. The plugin internally caches the data, but getting the instance repeatedly still involves some overhead.
- Add dependency: flutter pub add shared_preferences
- Import the package in your Dart file
- Get instance: await SharedPreferences.getInstance()
- Use the instance to read/write values
Reading and Writing Values
SharedPreferences supports primitive types: int, double, bool, String, and List<String>. To store a value, use the setter methods like `setString`, `setInt`, `setBool`, etc. For example, `prefs.setString('username', 'dhrumil')` saves a string. These methods return a Future<bool> indicating success.
Reading is synchronous once you have the instance. Use getters like `getString`, `getInt`, `getBool`, etc. They return null if the key doesn't exist, so you can provide a default value using the null-aware operator or by checking for null.
Remember that keys are case-sensitive strings. It's good practice to define them as constants to avoid typos. Also, be mindful of the data size: SharedPreferences is not meant for large datasets. Storing large strings or lists can impact performance, as the entire set is loaded into memory.
- Use setString, setInt, setBool, setDouble, setStringList
- Getters return null if key not found
- Define keys as constants for consistency
- Avoid storing large data; use a database for that
| Feature | SharedPreferences | sqflite | Hive | flutter_secure_storage |
|---|---|---|---|---|
| Data type | Key-value (primitives) | Relational | Key-value (any object) | Key-value (encrypted) |
| Typical use case | Small preferences | Structured data | Fast local storage | Sensitive data |
| Performance | Fast for small data | Good with indexes | Very fast | Slower due to encryption |
| Setup complexity | Low | Medium | Low | Low |
| Encryption | No | No | No | Yes |
| Max recommended size | < 100 KB | Unlimited (disk) | Unlimited (disk) | < 10 KB |
Handling Asynchronous Operations
Since `getInstance()` is asynchronous, you need to handle it properly. A common pattern is to use a FutureBuilder or to initialize in main and pass the instance down. For example, you can make your main function async and await the instance before running the app.
When writing values, the setters are also asynchronous but you often don't need to await them unless you need to ensure the write completed before proceeding. However, for critical data, awaiting is safer. Note that writes are persisted to disk asynchronously, so there's a tiny window where data might be lost if the app is killed immediately after.
If you're using state management like Provider or Riverpod, you can provide the SharedPreferences instance to your widget tree. This avoids repeated async calls and makes testing easier. For a deeper dive into state management, see our article on StatelessWidget vs StatefulWidget.
- Initialize in main: WidgetsFlutterBinding.ensureInitialized(); await SharedPreferences.getInstance()
- Use FutureBuilder for async loading
- Await setters for critical writes
- Consider dependency injection for testability
Testing with SharedPreferences
Testing code that uses SharedPreferences is straightforward thanks to the `setMockInitialValues` method. In your test setup, call `SharedPreferences.setMockInitialValues({})` to provide a clean mock. This allows you to test read/write logic without touching the actual disk.
For widget tests, you can set mock initial values before pumping the widget. Then, any calls to getInstance will return the mock data. This is essential for reliable unit tests. If you're new to testing, start with simple tests that verify your preferences logic.
Remember to reset the mock between tests to avoid state leakage. You can call setMockInitialValues again with an empty map in setUp or tearDown. This ensures each test runs in isolation.
- Use SharedPreferences.setMockInitialValues({}) in tests
- Set mock values before widget tests
- Reset mock between tests
- Test both read and write paths
Performance and Best Practices
SharedPreferences loads all data into memory when you call getInstance. For most apps with small preferences, this is negligible. However, if you store large lists or many keys, it can affect startup time. Keep your preferences lean; aim for under 100 keys and avoid storing large strings.
Writes are asynchronous and batched. The plugin uses platform-specific implementations (NSUserDefaults on iOS, SharedPreferences on Android) which handle disk I/O efficiently. But frequent writes (e.g., on every keystroke) can cause performance issues. Debounce writes or write only on significant events.
If you need to store complex objects, consider serializing to JSON and storing as a string, but be aware of size limits. For larger data, use a database like sqflite or hive. Also, be cautious with sensitive data: SharedPreferences is not encrypted by default. Use flutter_secure_storage for tokens and passwords.
- Keep preferences small (<100 keys)
- Avoid frequent writes; debounce if needed
- Serialize complex objects to JSON strings
- Use secure storage for sensitive data
Common Pitfalls and How to Avoid Them
One common mistake is forgetting to await getInstance, leading to null errors. Always ensure you have the instance before using it. Another pitfall is using the same key for different types, which causes a type error at runtime. Stick to consistent types per key.
Not handling null values properly can lead to crashes. Always provide defaults. Also, be aware that SharedPreferences is not reactive; if you change a value, other parts of your app won't automatically update. You need to manage state manually or use a state management solution.
Lastly, on Android, SharedPreferences is backed by XML files, and on iOS by plist files. While the plugin abstracts this, extreme cases like very large data can cause slow reads. Stick to the intended use: small, simple preferences.
- Always await getInstance
- Use consistent types for keys
- Provide default values for null
- Implement reactivity via state management
Key points
- SharedPreferences is ideal for small, simple key-value data like user preferences.
- Always await getInstance and handle async properly to avoid null errors.
- Use setMockInitialValues for reliable testing.
- Avoid storing large or sensitive data; choose the right tool for the job.
Flutter Screen Widget and Cost Estimator
Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.
Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.