How to Use Shared preferences in Flutter

Muhammad Affan Khan
2 min readMar 27, 2019

--

Photo by Jan Antonin Kolar on Unsplash

When building a mobile application, sooner or later, you come across a situation where you need to store your app’s settings or preferences and retrieve them when you need even after the app is restarted. The main advantage of using this technique is that the data you store remains intact even if the app is closed.

If you are building an app using native codebase(Java/Kotlin for Android or Swift/Objective-C for iOS), you will most probably be using Shared preferences(Android) or NSUserDefaults(iOS).

When it comes to Flutter, it’s quite easy and straightforward to achieve this functionality. Flutter provides you a package called shared_preferences that behind the scene, uses Shared preferences on Android and NSUserDefaults on iOS. It stores data in the form of key-value pairs.

Here is how you can install and use this package:

Install the Package

In the pubspec.yaml file of your project’s root directory, add the following line:

dependencies:   
shared_preferences: ^0.5.1+2

Next, run the following command to install the newly added dependency:

$ flutter packages get

Start using Shared preferences

Import the Shared preferences package in your dart file like this:

import 'package:shared_preferences/shared_preferences.dart';

Now, wherever you need to save any key-value pair, you can save like this:

Saving Data

SharedPreferences myPrefs = await SharedPreferences.getInstance();myPrefs.setInt('age',20);
myPrefs.setString('name','Muhammad Hussain');
myPrefs.setBool('syncData', false);

One important thing to note is that the above code should be written in an async method because getting shared preferences object takes a little while.

Retrieving Data

SharedPreferences myPrefs = await SharedPreferences.getInstance();final String name = myPrefs.getString('name');
final int age = myPrefs.getInt('age');
final bool syncData = myPrefs.getBool('syncData');

Note, the keys used to save and retrieve the data should be the same.

--

--

Muhammad Affan Khan

Software Engineer | Ruby on Rails | Flutter | Open source lover