This article describes the notion of Shared Preferences that allows a Flutter application (Android or iOS) to save settings, properties, data in the form of key-value pairs that will persist even when the user closes the application.

Difficulty: Beginner

Shared Preferences are stored in XML format.

Shared Preferences is application specific, i.e. the data is lost on performing one of the following options:

  • on uninstalling the application
  • on clear the application data

Main use

The main use of Shared Preferences is to save user preferences, settings, maybe data (if not too large) so that next time the application is launched, these pieces of information could be retrieved and used.

Overview of the API

Full documentation can to be found in the Flutter packages repository.

1. Getters

Set < String > getKeys() Returns all keys

dynamic get(String key) Returns the value, associated with the corresponding key

bool getBool(String key) Returns the boolean value, associated with the corresponding key. If the value is not a boolean, throws an exception.

int getInt(String key) Returns the integer value, associated with the corresponding key. If the value is not an integer, throws an exception.

double getDouble(String key) Returns the double value, associated with the corresponding key. If the value is not a double, throws an exception.

String getString(String key) Returns the string value, associated with the corresponding key. If the value is not a string, throws an exception.

List getStringList(String key) Returns a set of string values, associated with the corresponding key. If the value is not a string set, throws an exception.

2. Setters

Future < bool > setBool(String key, bool value) Saves a boolean value and associated with the key.

Future < bool > setInt(String key, int value) Saves an integer value and associated with the key.

Future < bool > setDouble(String key, double value) Saves a double value and associated with the key.

Future < bool > setString(String key, String value) Saves a string value and associated with the key.

Future < bool > setStringList(String key, List value) Saves a list of string values and associated with the key.

3. Removal

Future < bool > remove(String key) Removes the key-pair associated with the key.

Also, in any setter, the fact of passing a null value, corresponds to calling a remove(key).

Future < bool > clear async Removes all the key-pairs linked to the application package.

How to use?

pubspec.yaml

In the pubspec.yaml, add the shared_preferences to the list of dependencies, as follows:

dependencies:
  flutter:
    sdk: flutter

  flutter_localizations:
    sdk: flutter
    
  shared_preferences: ^0.4.2

Practical use

The following piece of code simulates a class that needs to deal with a user preference (e.g. allow notifications, sorting order)

import 'package:shared_preferences/shared_preferences.dart'

class SharedPreferencesTest {
  ///
  /// Instantiation of the SharedPreferences library
  ///
  final String _kNotificationsPrefs = "allowNotifications";
  final String _kSortingOrderPrefs = "sortOrder";

  /// ------------------------------------------------------------
  /// Method that returns the user decision to allow notifications
  /// ------------------------------------------------------------
  Future<bool> getAllowsNotifications() async {
	final SharedPreferences prefs = await SharedPreferences.getInstance();

  	return prefs.getBool(_kNotificationsPrefs) ?? false;
  }

  /// ----------------------------------------------------------
  /// Method that saves the user decision to allow notifications
  /// ----------------------------------------------------------
  Future<bool> setAllowsNotifications(bool value) async {
	final SharedPreferences prefs = await SharedPreferences.getInstance();

	return prefs.setBool(_kNotificationsPrefs, value);
  }

  /// ------------------------------------------------------------
  /// Method that returns the user decision on sorting order
  /// ------------------------------------------------------------
  Future<String> getSortingOrder() async {
	final SharedPreferences prefs = await SharedPreferences.getInstance();

	return prefs.getString(_kSortingOrderPrefs) ?? 'name';
  }

  /// ----------------------------------------------------------
  /// Method that saves the user decision on sorting order
  /// ----------------------------------------------------------
  Future<bool> setSortingOrder(String value) async {
	final SharedPreferences prefs = await SharedPreferences.getInstance();

	return prefs.setString(_kSortingOrderPrefs, value);
  }
}

Conclusions

As you can see, it is straightforward to use this package.

The hereabove code is only meant to show how to invoke the package. In practice, it is more likely that you will not have one getter/setter per setting…

Keep in mind that Shared Preferences are not encrypted therefore, it is not recommended to put any sensitive data, such as a password for example.

Stay tuned for new articles and happy coding.


This article is also available on Medium - Flutter Community