DEV Community

Cover image for Shared Preferences with Flutter
Ishan Sharma
Ishan Sharma

Posted on

Shared Preferences with Flutter

Originally Published On My Personal Blog.
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

    dependencies:
      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

      import '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.

    var sp = await SharedPreferences.getInstance();
    sdp.setString('key', 'value');
    var 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.

    import 'package:shared_preferences/shared_preferences.dart';
    
    class StorageService{
    
      static StorageService _service;   
    
      static SharedPreferences _pref;
    
      static Future<StorageService> createInstance() async{
        if(_service==null){
          /* If service is not initialized */
          var _= StorageService._();    //Creates a local instance of service
    
          /* Creates an instance of Shared Preferences*/
          await _._getInstance();
    
          _service = _;
        }
    
        /* If service is already created return that */
        return _service;
      }
    
      void _getInstance() async {
        _pref = await _pref.getInstance();
      }
    
      /* This method accepts a key and returns, it's value*/
      static dynamic getValueFromKey(String key){
        if(_pref==null) return null;
        return _pref.get(key);
      }
    
      /* This method sets a String and returns true, if set succesfully*/
      static bool setValueAndKey(String key, String value){
        if(_pref==null) return null;
        return _pref.setString(key, value);
      }
    
    }
    

    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

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

    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 :

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

    To retrieve the same, we can use :

    StorageService.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.

Let us discuss in the comments, what's your preferred way of storing data in persistent storage in Flutter or React-Native or any other ;)

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

Top comments (3)

Collapse
 
m3_ph3 profile image
PH3N0M3N0L

Thanks for this in-depth article! đź’™

Would love to see more of these, focused on Flutter!

Collapse
 
kasunthilina profile image
Kasun Thilina Thennakoon

Great article. Did you try out injecting the shared preferences and using with Provider ?

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more