...

/

Key-Value Store

Key-Value Store

Learn to persist data in a key-value store.

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.
Press + to interact
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:

Press + to interact
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: ...