Storing data locally in mobile applications is a fundamental requirement for a myriad of use cases, one of which includes saving user preferences or caching data for faster retrieval. In Flutter, one of the most popular solutions for this is the SharedPreferences
library. In this guide, we'll delve deep into how to effectively use SharedPreferences
in Flutter applications.
Understanding SharedPreferences in Flutter
SharedPreferences is a persistent storage solution used by both Android and iOS applications. It allows apps to store simple key-value pairs, which persist even after the app is closed or restarted. This makes it an ideal choice for storing lightweight data such as user settings, flags, or counters.
In Flutter, the shared_preferences
plugin provides a seamless interface to SharedPreferences for both Android (using Android's SharedPreferences) and iOS (using NSUserDefaults).
Setting Up SharedPreferences in Your Flutter Project
Before diving into the code, let's set up our environment:
Flutter SDK Setup
Ensure you have the Flutter SDK installed. If not, you can download and install it from the official Flutter website for your specific OS (Windows, macOS, Linux, or Chrome OS). After installation, verify the installation by running:
flutter --version
Integrating the shared_preferences Plugin
To integrate shared_preferences
into your Flutter project:
- Open your
pubspec.yaml
file. - Under
dependencies
, add:
shared_preferences:
- Run
flutter pub get
to install the new dependency. - Import the plugin in your Dart file:
import 'package:shared_preferences/shared_preferences.dart';
Storing and Retrieving Data with SharedPreferences
Storing Data
SharedPreferences supports various primitive data types. Here's how you can store them:
- Integer:
prefs.setInt('key', value);
- String:
prefs.setString('key', value);
- Boolean:
prefs.setBool('key', value);
- Double:
prefs.setDouble('key', value);
Retrieving Data
Fetching data is straightforward:
- Integer:
int value = prefs.getInt('key');
- String:
String value = prefs.getString('key');
- Boolean:
bool value = prefs.getBool('key');
- Double:
double value = prefs.getDouble('key');
If the key doesn't exist, the getter methods will return null
.
Deleting Data
To delete a specific key-value pair:
prefs.remove('key');
Checking Data Existence
To verify if a key exists:
bool exists = prefs.containsKey('key');
Practical Implementation: Persisting Counter Value
Consider a simple Flutter app with a counter. Every time the user presses a button, the counter increments. By default, if the user closes and reopens the app, the counter resets. Let's change this behavior using SharedPreferences
.
- First, initialize SharedPreferences:
SharedPreferences prefs = await SharedPreferences.getInstance();
When incrementing the counter, save the new value:
_counter++;
prefs.setInt('counter', _counter);
When the app starts, retrieve the saved counter value:
_counter = prefs.getInt('counter') ?? 0;
Now, even if the user closes the app, the counter value will persist and be retrieved upon the next launch.
Implementing a Splash Screen Using SharedPreferences
A common use case is to show a splash screen or intro slider only on the first app launch. With SharedPreferences
, this becomes trivial.
- Check if a key (e.g.,
firstLaunch
) exists in SharedPreferences. - If it doesn't, show the splash screen and set the key.
- On subsequent launches, since the key exists, skip the splash screen.
FAQs
1. What is SharedPreferences in Flutter?
SharedPreferences is a local storage solution allowing Flutter apps to store simple key-value pairs.
2. Is SharedPreferences secure for sensitive data?
No, it's not recommended for storing sensitive data like passwords or encryption keys. Consider more secure solutions for such requirements.
3. Can I store complex objects in SharedPreferences?
SharedPreferences is designed for primitive data types. For complex objects, consider serializing them into strings before storing.
4. Does SharedPreferences data persist after app updates?
Yes, the data remains intact even after app updates. However, it will be cleared if the user uninstalls the app.