Using SharedPreferences in Flutter for Local Data Storage

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.

sequenceDiagram User->>App: Launch App App->>SharedPreferences: Check if key exists SharedPreferences-->>App: Return value or null App->>User: Show content based on key existence User->>App: Perform action (e.g., increment counter) App->>SharedPreferences: Save new data

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:

Bash
flutter --version

Integrating the shared_preferences Plugin

To integrate shared_preferences into your Flutter project:

  1. Open your pubspec.yaml file.
  2. Under dependencies, add:
YAML
shared_preferences:
  1. Run flutter pub get to install the new dependency.
  2. Import the plugin in your Dart file:
Dart
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:

Dart
prefs.remove('key');

Checking Data Existence

To verify if a key exists:

Dart
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.

  1. First, initialize SharedPreferences:
Dart
SharedPreferences prefs = await SharedPreferences.getInstance();

When incrementing the counter, save the new value:

Dart
_counter++;
prefs.setInt('counter', _counter);

When the app starts, retrieve the saved counter value:

Dart
_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.

  1. Check if a key (e.g., firstLaunch) exists in SharedPreferences.
  2. If it doesn't, show the splash screen and set the key.
  3. 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.

Author