Navigate back to the homepage

Shared Preferences with Flutter

Ishan Sharma
August 23rd, 2020 · 3 min read

I have been playing with Flutter for almost 7 months now, and I’m enjoying every second of it. The main factor that I love about Flutter is that it enables you to be more creative and bring out that artist in you. As I have mentioned earlier in one of my articles, “Programming is all about embracing that artist in you 🎨”.

The first tools that allowed me to get a sense of the same were ‘HTML & CSS’, they gave me the possibility of having this large empty canvas on the web and paint it in whichever way I want, while also giving me the ability to share it with anyone.

For those of you, who don’t know what Flutter is, here’s a brief introduction

What Is Flutter?

Flutter is a UI toolkit by Google and the open-source community which allows you to build beautiful, natively compiled applications for mobile, web, and desktop while maintaining a single codebase.

NOTE: If you haven’t started out with Flutter yet and are planning to do the same, then this article will not be much beneficial to you

If you’d like to get started with flutter, refer to flutter’s official documentation. It’s one of the best documentation, I’ve ever read.

For those of you, who do know their way around, Let’s jump right in.

What is Shared Preferences?

When you’re working on some client apps, you’ll often come across situations, where you need to store some data in the persistent storage of devices. For example, let’s say you’re using some OAuth client for one of your login methods, for that you’ll need to store the access token on the client’s device so that the client does not have to sign in again on relaunching the app.

Shared Preferences is one of the ways to do it. It provides a way of reading and storing such data in a key-value pair.

Please keep in mind that, by default the Flutter SDK does not come with any support for Shared Preferences. Luckily, The Flutter Team has built a package that helps to achieve the same, ‘shared_preferences’.

Under the hood, it uses NSUserDefaults on iOS and SharedPreferences on Android to do it’s magic.

Let’s see a quick sample on how to work with the same.

  1. Adding shared_preferences in pubspec.yaml

    1dependencies:
    2 shared_preferences: ^0.5.10

    At the time of writing this article, the latest version of the package is 0.5.10. You can surely use whichever is latest.

    Once you’re done with above, just run flutter pub get in your terminal to get the packages.

  2. Import the package in your dart file

    1import 'package:shared_preferences/shared_preferences.dart';
  3. Using the package

    Now, that we’ve everything set up, let’s dive into using it.

    Here’s is the typical usage of how we can use SharedPreferences to set & get any key-value pair.

    1var sp = await SharedPreferences.getInstance();
    2sdp.setString('key', 'value');
    3var saved_val = sp.getString('key');

    But, this can add up to a lot of boilerplate add junk up your project code pretty quickly, plus it’s not so easier to maintain a projec with code like this, and can occur to unnecessary debugging.

    So, instead of using this and writing so much boilerplate code every time, we can create a helper service that will handle everything related to Shared Preferences.

    1import 'package:shared_preferences/shared_preferences.dart';
    2
    3class StorageService{
    4
    5 static StorageService _service;
    6
    7 static SharedPreferences _pref;
    8
    9 static Future<StorageService> createInstance() async{
    10 if(_service==null){
    11 /* If service is not initialized */
    12 var _= StorageService._(); //Creates a local instance of service
    13
    14 /* Creates an instance of Shared Preferences*/
    15 await _._getInstance();
    16
    17 _service = _;
    18 }
    19
    20 /* If service is already created return that */
    21 return _service;
    22 }
    23
    24 void _getInstance() async {
    25 _pref = await _pref.getInstance();
    26 }
    27
    28 /* This method accepts a key and returns, it's value*/
    29 static dynamic getValueFromKey(String key){
    30 if(_pref==null) return null;
    31 return _pref.get(key);
    32 }
    33
    34 /* This method sets a String and returns true, if set succesfully*/
    35 static bool setValueAndKey(String key, String value){
    36 if(_pref==null) return null;
    37 return _pref.setString(key, value);
    38 }
    39
    40}

    and just like that, we’re done with creating a service for our Shared Preferences.

    It’s actually a good practice to create an instance of this service, before we run our app. Doing this is pretty simple and straight-forward.

    In our main.dart file, Let’s convert our main function to async

    1void main() async{
    2 runApp(myApp);
    3 /*Just make sure to add this line*/
    4 await StorageService.createInstance();
    5}

    and that’s it. With all that set-up, we can easily use our service to store or read data from the storage.

    To set a String in persistent storage, we can use :

    1StorageService.setValueAndKey("access_token", "771jkh21y3ubnm21behd21");

    To retrieve the same, we can use :

    1StorageService.getValueFromKey("access_token");

When To Use Shared Preferences?

Now that you’ve got a basic crux of how easy it is to use Shared Preferences in flutter, the real question arises is how to decide when to use shared_preferences or sqflite or others.

It all comes down to your problem statement, on what you’re looking for. If you’re planning to store just some access_token or todo list tasks or maybe user’s app preferences such as dark theme etc. Basically, If you’re planning to store small values, then Shared Preferences is the optimal solution. We don’t usually use sqflite for storing small values, because then you’ll have to write a lengthy boilerplate and supporting classes.

But, please keep in mind that Shared Preferences should not be used as a solution for storing complex relational data on a device.

That’s all for now, catch you guys in the next one 👋🏻.

Join our email list and get notified about new content

Be the first to receive our latest content with the ability to opt-out at anytime. We promise to not spam your inbox or share your email with any third parties.

More articles from Ishan Sharma

Intro To Linux

I'll explain what linux is and why, as a developer, using Linux will be beneficial for you.

July 8th, 2020 · 6 min read

A Quick Dive Into ES6

Let's quickly learn about almost all the features of the ES6 JS and how they are essential for react or other JS frameworks.

July 5th, 2020 · 4 min read
© 2020 Ishan Sharma
Link to $https://twitter.com/ishandeveloperLink to $https://github.com/ishandeveloperLink to $https://www.linkedin.com/in/ishandeveloperLink to $https://stackoverflow.com/users/13219775/ishandeveloperLink to $https://medium.com/@ishandeveloper