Shared Preferences with Flutter
Tags: flutter, database, dart, storage
Published: 2020-08-23 20:10:33

Originally Published On [My Personal Blog](https://blog.ishandeveloper.com).
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](https://blog.ishandeveloper.com/new-lang-framework), ***"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](https://google.org) 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](https://flutter.dev/docs/get-started). 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'](https://pub.dev/packages/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

    ```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

    <!--DART DOES NOT WORK WITH PRISM ON MY SITE, SO USE JS INSTEAD FOR HIGHLIGHTING-->
    ```dart
      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.
    <!--DART DOES NOT WORK WITH PRISM ON MY SITE, SO USE JS INSTEAD FOR HIGHLIGHTING-->
    ```dart
    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.

    <!--DART DOES NOT WORK WITH PRISM ON MY SITE, SO USE JS INSTEAD FOR HIGHLIGHTING-->
    ```dart
    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

    ```dart
    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 : 
    ```dart
    StorageService.setValueAndKey("access_token", "771jkh21y3ubnm21behd21");
    ```

    To retrieve the same, we can use : 
    ```dart
    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](https://pub.dev/packages/shared_preferences) or [sqflite](https://pub.dev/packages/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](https://pub.dev/packages/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 👋🏻.