LibraryShared Preferences for Simple Data

Shared Preferences for Simple Data

Learn about Shared Preferences for Simple Data as part of Flutter App Development with Dart

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

code
shared_preferences
package, which offers a simple key-value store mechanism.

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

code
SharedPreferences
on Android and
code
NSUserDefaults
on iOS), making it efficient for small data storage.

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

code
shared_preferences
package to your Flutter project. Open your
code
pubspec.yaml
file and add the following under
code
dependencies
:

yaml
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2 # Use the latest version

After saving

code
pubspec.yaml
, run
code
flutter pub get
in your terminal to download and install the package.

Saving Data

To save data, you'll use the

code
SharedPreferences
instance. You'll typically get an instance using
code
SharedPreferences.getInstance()
. Then, you can use methods like
code
setString()
,
code
setInt()
,
code
setBool()
, etc., providing a unique key and the value you want to store.

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):

dart
import 'package:shared_preferences/shared_preferences.dart';
Future saveDarkModePreference(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

code
get
(e.g.,
code
getString()
,
code
getInt()
,
code
getBool()
). These methods also require the key you used when saving the data. Importantly, these methods return a
code
Future
, so you'll need to
code
await
them. If the key doesn't exist, they will return
code
null
or a default value if you provide one.

Here's how you might retrieve the dark mode preference:

dart
import 'package:shared_preferences/shared_preferences.dart';
Future getDarkModePreference() async {
final prefs = await SharedPreferences.getInstance();
// Provide a default value if the key doesn't exist
return prefs.getBool('darkModeEnabled') ?? false;
}

Removing Data

You can also remove specific key-value pairs using the

code
remove()
method, or clear all stored data using
code
clear()
.

Example of removing a specific preference:

dart
Future removeUserName() 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

code
Future
returned by
code
SharedPreferences
methods using
code
async
/
code
await
. Provide default values when retrieving data to gracefully handle cases where a key might not exist yet. Be mindful of security; Shared Preferences are not encrypted and should not be used for sensitive data like passwords or API keys.

Learning Resources

Flutter Shared Preferences Package Documentation(documentation)

The official documentation for the shared_preferences plugin, detailing installation, usage, and available methods.

Flutter Docs: Working with Forms and User Input(documentation)

Learn how to handle user input in Flutter, which often involves saving preferences.

Flutter Shared Preferences Tutorial by Fireship(video)

A concise and engaging video tutorial explaining how to use shared preferences in Flutter.

Flutter Shared Preferences: Save and Load Data by The App Expert(video)

A step-by-step guide on implementing shared preferences for data persistence in Flutter applications.

Flutter Shared Preferences Example(blog)

A practical example demonstrating how to save and retrieve various data types using shared preferences in Flutter.

Flutter Shared Preferences: A Complete Guide(blog)

A comprehensive guide covering the basics, advanced usage, and best practices for shared preferences in Flutter.

Flutter State Management: Shared Preferences(blog)

Discusses shared preferences as a simple state management solution for small data in Flutter.

SharedPreferences (Android Developers)(documentation)

Understand the underlying Android mechanism that Flutter's shared_preferences plugin utilizes.

UserDefaults (Apple Developer Documentation)(documentation)

Explore the equivalent mechanism for storing preferences on iOS platforms.

Flutter Persistence Options(documentation)

An overview of different data persistence strategies in Flutter, placing shared preferences in context.