Search⌘ K
AI Features

Key-Value Store

Explore how to implement key-value data persistence in Flutter applications using the shared_preferences plugin. Learn to save, retrieve, and remove strings, numbers, and booleans while managing app state like theme preferences, enhancing user experience with persistent settings.

In this lesson, we’ll use the shared_preferences plugin to store a small amount of key-value pair data. Let’s modify the app below.

// Route constants
const String productsOverviewRoute = '/';
const String productDetailRoute = '/product-detail';
const String cartScreenRoute = '/cart-screen';
const String settingsScreenRoute = '/settings-screen';

// Prefs Constants
//TODO-2: Add string unique key
//TODO-5: Add number unique key
//TODO-8: Add bool unique key

E-commerce app initial code

Adding the dependency

To use shared_preferences, we first need to add the dependency to our application:

  1. Open the pubsbec.yaml file and locate # TODO-1: Add shared shared_preferences plugin.
  2. Add the shared_preferences plugin. Be careful with the indentation; the plugin should align with the provider package.
YAML
shared_preferences: ^2.0.12
  1. Rerun the app.

Whenever we want to use the plugin, we will have to import it at the top of any file:

Dart
import 'package:shared_preferences/shared_preferences.dart';

Working with strings

We’ll first need to give our string a unique key. In lib/constants.dart file, locate //TODO-2: Add string unique key and add the constant given below:

Dart
const prefStringKey = 'username';

Saving strings

...