How to use Shared Preferences in Flutter?

Shared preferences are collections of key-value data. The values can be an Integer or String. In this tutorial, we will show you how to use Shared preferences in Flutter using the shared_preferences package.shared_preferences provides you API by wrapping platform-specific persistent storage (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.) to save and retrieve data in the form of key, value pair.

Here are the step by step instructions for using the shared_preferences package in Flutter.

Install Package

Add shared_preferences to pubspec.yaml as shown in below. There are no other configurations required for the plugin on both iOS and Android operating systems.

Initialize Shared Preferences

You need to initialize shared_preferences if it does not exist. For initializing, create and call sharedPrefInit() from the main function as shown in the code below. It checks if a key "app-name" exist. If Shared Preferences are not initialized, this will throw an error. SharedPreferences .setMockInitialValues({}) initializes it.

Put Values

The code below shows how to put a string, integer, list or object values to Shared Preferences. You cannot add Json objects directly to shared preferences. Here list or object are first encoded to JSON string using jsonEncode() and stored as String in Shared Preferences.

Get Values

Here we show, how to retrieve a value from Shared Preferences data collection providing the key. In case of Json object we receive the value as string, which we are converting back to Json using the jsonDecode function.

Reset Shared Preferences

You can clear all values stored in shared preferences using clear() function as shown below.