How to save to local storage (shared preferences) in Flutter

Share this post

To save to local storage or Shared Preferences (as it’s called in Android) in Flutter, you can use the shared_preferences plugin. First of all, you have to add the dependency to your pubspec.yaml file:

    sdk: flutter
  shared_preferences: "<newest version>"

Writing data to local storage in Flutter

You can write data to local storage is easy. We just need to get an instance of our SharedPreferences object and call our set function depending on the type of our data. You could write your save function as follows:

// we have an async function because getInstance() return a Future
_saveData() async {
    // we make sure we have an instance
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt('yourKey', 100);

In addition to int you can save the following types of data:

  • bool: setBool()
  • double: setDouble()
  • String: setString()
  • List<String>: setStringList()

Shared Preferences is intended for storing a relatively small amount of data and is usually suitable for saving user’s preferences. For example, if a user wants to use your app in dark mode, that setting should be saved somewhere and this is a perfect use case for Shared Preferences.

Reading local storage in Flutter

To read the data that we have saved previously, we can do the following:

// our return value is Future<int> because we have to "await" an instance
Future<int> _getData() async {
    final prefs = await SharedPreferences.getInstance();
    // we make sure we have some value to set it to 0 if there is no value
    return prefs.getInt('yourKey') ?? 0;

Obviously, there are get methods for other types as well, just try it out yourself.

Removing data from local storage in Flutter

To remove data we can simply call remove providing our key:

_removeData() async {
    final prefs = await SharedPreferences.getInstance();