SharedPreference

If you have a relatively small collection of key-values to save, you can use the shared_preferences plugin. The shared preferences plugin wraps NSUserDefaults on iOS and SharedPreferences on Android, providing a persistent store for simple data.

SharedPreference can store only primitive type data. It is not designed to store data type like List, Map, or Stream or any other data type. You can only store int, string, bool, double and stringList. SharedPreference is also not good idea when you want to store a lot of information, like more than 2MB data.

First add the dependencies:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

After installing the package, import the plugin in your dart file:

import 'package:shared_preferences/shared_preferences.dart';

After that, the first thing you must do is to obtain the instance of SharedPreference:

final prefs = await SharedPreferences.getInstance();

Now you can call various methods using the prefs object.

Saving Data

To persist data, use the setter methods provided by the SharedPreferences class. Setter methods are available for various primitive types, such as setInt, setBool, and setString.

// obtain shared preferences
final prefs = await SharedPreferences.getInstance();

// set value
prefs.setInt('counter', counter);

Read Data

To read data, use the appropriate getter method provided by the SharedPreferences class. For each setter there is a corresponding getter. For example, you can use the getInt, getBool, and getString methods.

final prefs = await SharedPreferences.getInstance();

// Try reading data from the counter key. If it doesn't exist, return 0.
final counter = prefs.getInt('counter') ?? 0;

Remove Data

To delete data, use the remove() method.

final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');