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:
- Open the
pubsbec.yamlfile and locate# TODO-1: Add shared shared_preferences plugin. - Add the
shared_preferencesplugin. Be careful with the indentation; the plugin should align with theproviderpackage.
- Rerun the app.
Whenever we want to use the plugin, we will have to import it at the top of any file:
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: