Learn how to use SharedPreferences in Flutter for persistent storage of simple data types, ideal for user preferences and settings.
In the journey of developing a Flutter application, one of the essential aspects is managing user preferences and settings. This is where SharedPreferences
comes into play. It provides a simple way to store and retrieve small pieces of data that need to persist between app launches. In this section, we’ll delve into the details of using SharedPreferences
in Flutter, covering everything from setup to practical use cases.
SharedPreferences
is a key-value storage system that allows you to store simple data types persistently on a user’s device. It supports data types such as int
, double
, bool
, String
, and List<String>
. This makes it ideal for storing user preferences, application settings, and other small pieces of data that need to be retained between app sessions.
SharedPreferences
persists across app launches.To use SharedPreferences
in your Flutter project, you need to add the shared_preferences
package to your pubspec.yaml
file. This package provides the necessary functionality to interact with the shared preferences storage.
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.13
Note: Always check for the latest version of the
shared_preferences
package on pub.dev and update the version number accordingly.
After adding the dependency, run the following command to fetch the package:
flutter pub get
Once the package is added to your project, you can import it into your Dart files where you need to use shared preferences:
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences
provides several methods for storing data, each corresponding to a specific data type. These methods are asynchronous and return a Future<bool>
, indicating whether the operation was successful.
setInt(String key, int value)
: Stores an integer value.setDouble(String key, double value)
: Stores a double value.setBool(String key, bool value)
: Stores a boolean value.setString(String key, String value)
: Stores a string value.setStringList(String key, List<String> value)
: Stores a list of strings.Here’s an example of storing a user’s theme preference:
Future<void> saveThemePreference(bool isDarkMode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('isDarkMode', isDarkMode);
}
Retrieving data from SharedPreferences
is just as straightforward as storing it. You use the corresponding get
methods to retrieve the data.
getInt(String key)
: Retrieves an integer value.getDouble(String key)
: Retrieves a double value.getBool(String key)
: Retrieves a boolean value.getString(String key)
: Retrieves a string value.getStringList(String key)
: Retrieves a list of strings.If the key does not exist, these methods return null
. It’s a good practice to handle these cases by providing default values.
Here’s how you can retrieve the user’s theme preference:
Future<bool> getThemePreference() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('isDarkMode') ?? false; // Return false if key doesn't exist
}
Let’s consider a practical example where you want to manage a user’s theme preference (light or dark mode) in your Flutter app. This involves saving the user’s choice and applying it when the app is launched.
When the user selects a theme, you save their preference using SharedPreferences
:
Future<void> saveThemePreference(bool isDarkMode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('isDarkMode', isDarkMode);
}
When the app is launched, you retrieve the saved preference and apply the theme accordingly:
Future<bool> getThemePreference() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('isDarkMode') ?? false; // Default to light mode if not set
}
You can use the retrieved preference to set the theme when building your app’s UI:
bool isDarkMode = await getThemePreference();
ThemeData theme = isDarkMode ? ThemeData.dark() : ThemeData.light();
While SharedPreferences
is a powerful tool for storing simple data, it’s important to be aware of its limitations and considerations:
SharedPreferences
is not designed for storing large amounts of data or complex objects. For such use cases, consider using a database like SQLite or a cloud-based solution.SharedPreferences
is stored in plain text. Avoid storing sensitive information such as passwords or personal data. For sensitive data, consider using secure storage solutions.SharedPreferences
operations are asynchronous, ensure you handle them appropriately to avoid blocking the UI thread.SharedPreferences
. Use secure storage solutions for such data.To better understand the process of saving and retrieving data with SharedPreferences
, refer to the following flowchart:
flowchart TD A[Start] --> B[Get SharedPreferences Instance] B --> C{Save Data?} C -->|Yes| D[Use set methods to save data] C -->|No| E{Retrieve Data?} E -->|Yes| F[Use get methods to retrieve data] E -->|No| G[End]
SharedPreferences
is an essential tool in Flutter for managing user preferences and small pieces of persistent data. By understanding how to effectively use this plugin, you can enhance your app’s user experience by retaining settings and preferences across sessions. Remember to consider its limitations and follow best practices to ensure your app remains efficient and secure.