Flutter Shared Preferences: Storing Simple Data
In Flutter app development, you often need to store small amounts of data locally on the user's device. This could include user settings, preferences, or simple state information. For these use cases, Flutter provides the
shared_preferences
What are Shared Preferences?
Shared Preferences is a Flutter plugin that allows you to save and retrieve primitive data types (like booleans, integers, doubles, strings, and string lists) in a persistent, asynchronous, and simple key-value store. It's built on top of native platform APIs (like
SharedPreferences
NSUserDefaults
Shared Preferences is ideal for storing user settings and simple data locally.
Think of Shared Preferences like a digital notebook where you can jot down small pieces of information, like whether a user has enabled dark mode or their username. Each piece of information is labeled with a unique 'key' so you can easily find it later.
The shared_preferences
package acts as an abstraction layer over the native platform's key-value storage. On Android, this is typically SharedPreferences
, and on iOS, it's NSUserDefaults
. These native mechanisms are designed for storing small amounts of data efficiently. The Flutter plugin makes it cross-platform and easy to use within your Dart code.
Adding the `shared_preferences` Package
To use Shared Preferences, you first need to add the
shared_preferences
pubspec.yaml
dependencies
dependencies:flutter:sdk: fluttershared_preferences: ^2.2.2 # Use the latest version
After saving
pubspec.yaml
flutter pub get
Saving Data
To save data, you'll use the
SharedPreferences
SharedPreferences.getInstance()
setString()
setInt()
setBool()
Imagine you want to save a user's name. You'd get an instance of SharedPreferences
, then call setString('userName', 'Alice')
. The setString
method takes two arguments: the key (a unique string identifier, like 'userName') and the value (the string 'Alice' in this case). This operation is asynchronous, so you'll need to await
it.
Text-based content
Library pages focus on text content
Here's a code snippet for saving a boolean value (e.g., for a dark mode toggle):
import 'package:shared_preferences/shared_preferences.dart';FuturesaveDarkModePreference(bool isDarkMode) async { final prefs = await SharedPreferences.getInstance();await prefs.setBool('darkModeEnabled', isDarkMode);}
Retrieving Data
To retrieve data, you use similar methods, but they are prefixed with
get
getString()
getInt()
getBool()
Future
await
null
Here's how you might retrieve the dark mode preference:
import 'package:shared_preferences/shared_preferences.dart';FuturegetDarkModePreference() async { final prefs = await SharedPreferences.getInstance();// Provide a default value if the key doesn't existreturn prefs.getBool('darkModeEnabled') ?? false;}
Removing Data
You can also remove specific key-value pairs using the
remove()
clear()
Example of removing a specific preference:
FutureremoveUserName() async { final prefs = await SharedPreferences.getInstance();await prefs.remove('userName');}
Remember that Shared Preferences is designed for small amounts of data. For larger or more complex data structures, consider using other storage solutions like SQLite databases or file storage.
Use Cases for Shared Preferences
Shared Preferences are excellent for:
- User Preferences: Storing themes (dark/light mode), language settings, notification preferences.
- Session Management: Storing a boolean flag indicating if a user is logged in.
- Simple State: Remembering the last viewed item or a user's input in a form.
- Onboarding Status: Tracking if a user has completed the initial app tutorial.
Key Considerations
Always handle the
Future
SharedPreferences
async
await
Learning Resources
The official documentation for the shared_preferences plugin, detailing installation, usage, and available methods.
Learn how to handle user input in Flutter, which often involves saving preferences.
A concise and engaging video tutorial explaining how to use shared preferences in Flutter.
A step-by-step guide on implementing shared preferences for data persistence in Flutter applications.
A practical example demonstrating how to save and retrieve various data types using shared preferences in Flutter.
A comprehensive guide covering the basics, advanced usage, and best practices for shared preferences in Flutter.
Discusses shared preferences as a simple state management solution for small data in Flutter.
Understand the underlying Android mechanism that Flutter's shared_preferences plugin utilizes.
Explore the equivalent mechanism for storing preferences on iOS platforms.
An overview of different data persistence strategies in Flutter, placing shared preferences in context.