Welcome to Our Website

Shared Preferences & Get Storage in Flutter

flutter storage plugins

There may come a time when you want to store some data in your Flutter app so you can reuse it later. A common use case for this functionality is storing login credentials to be recalled the next time the user launches the app.

There are multiple way to store data in flutter depending on developer preferences. There are most used plugins from which i am going to talk about Shared Preferences and Get Storage.

Shared Preferences

The data stored in SharedPreferences can be edited and deleted and it work asynchronously. SharedPreferences stores the data in a key-value pair.

This Plugin support almost all plat-from that is supported by flutter.This plugin wraps NSUserDefaults on iOS and SharedPreferences on Android.

Install

Now that we have the Flutter SDK ready and set, it’s time to install the shared_preferences plugin.

Open the pubspec.yaml file and add shared_preferences in the dependencies section:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: latest_version

This will install the latest version of the dependency.

To use the shared_preferences plugin, we have to import it into our file:

import 'package:shared_preferences/shared_preferences.dart';

The shared_preferences plugin exports a SharedPreferences class, which has methods that can be used to set data of various primitive types in SharedPreferences. It has a method, getInstance, which is used to create an instance of a SharedPreferences.

SharedPreferences prefs = await SharedPreferences.getInstance();

The getInstance creates and returns a SharedPreferences instance. The prefs holds the instance of SharedPreferences.

DataType Support

SharedPreferences support ready data types like int ,string ,bool ,double . Each primitive type has its corresponding getter & setter method. (Note: The key of the key-value pair is in string.)

Write Data

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('userId', 001);

In above code snippet we have added Integer value 001 at key name “userID” with method setInt(“key”,int_value) . Similarly we can add String value with method setString(“key”,”string_value”) , Bool value with setBool(“key”,bool_value) and Double with method setDouble(“key”,”double_value”) . This method are static inside SharedPreferences class.

Read Data

Now, let’s see how we can retrieve data from SharedPreferences. As we have setter methods for the primitive types so we have getter methods for retrieving data.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.getInt('userId');

In above code snippet we are able to read Integer value stored with key name “userID” with method getInt(“key”) . Similarly we can read String value with method getString(“key”) , Bool value with getBool(“key”) and Double with method getDouble(“key”) .

Verifying that data

We can check in SharedPreferences to see whether data exists before we either read or write. To do this, we’ll use the containsKey method.

The containsKey method accepts the key of the data in its arg and uses it to check whether the key exists in SharedPreferences.

The method returns a bool, true or false:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.containsKey('userId');
// true

In the above snippet, userId exists in the SharedPreferences. That’s why it returns true.

Delete Data

To remove data from the SharedPreferences, we’ll use the remove method. The key of the data is passed to the .remove(“key”) method so the key-value pair data in the SharedPreferences is deleted.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove("userId");

Here, the userId in the SharedPreferences is deleted.Also you can user .clear() method to clear all data in SharedPreferences


Get Storage

Get Storage is extra light weight & synchronous key-value pair package that will help you to store app data in memory such as, if user is signed in, if yes, then all the details about the user.

The GetX Storage is built completly built using dart programming language & we can easily integrate with GETX framework of flutter.

This Flutter package to store user data is fully tested & supported on most of the famous operating system which are supported by flutter.

Install

Now that we have the Flutter SDK ready and set, it’s time to install the get_storage plugin.

Open the pubspec.yaml file and add get_storage in the dependencies section:

dependencies:
  flutter:
    sdk: flutter
  get_storage: latest_version

This will install the latest version of the dependency.

To use the get_storage plugin, we have to import it into our file:

import 'package:get_storage/get_storage.dart';

Don’t forget to call GetStorage.init() method before loading the app / before calling runApp, it will initialize storage at the very beginning of app.

void main() async {
  //initialization
  await GetStorage.init();   
  runApp(MyApp());
}

The initialization is done at beginning so that if any data is been stored in device, it get loaded before the actual app

final myStorage = GetStorage();

The GetStorage creates and returns a GetStorage instance. The myStorage holds the instance of GetStorage.

DataType Support

GetStorage support ready data types like int , String, bool, double, Map and List . Each primitive type has its corresponding getter & setter method. (Note: The key of the key-value pair is in string.)

Write Data

myStorage.write('userId', 001);

In above code snippet we have added Integer value 001 at key name “userID” with method write(“key”,value) . Similarly we can add String ,Bool, Double, Map and List simply by just adding write(“key”, value). Unlike SharedPreferences this plugin does not have separate method for all data type.

Read Data

Now, let’s see how we can retrieve data from GetStorage.

myStorage.read('userId');

In above code snippet we are able to read Integer value stored with key name “userID” with method read(“key”). Similarly we can read String, Bool, Double, Map. and List with just method read(“key”).

Listen Data

GetStorage provide service to listen to change made in stored data which could be done like

myStorage.listenKey('userId', (value){
  print('new userId is $value');
});

In above code snippet we have attached a listener to key “userId”, so when-ever the userId changes or you change userId manually the code inside listenKey() method executes automatic.

Verifying that data

We can check in GetStorage to see whether data exists before we either read or write. To do this, we’ll use the hasData method.

The hasData method accepts the key of the data in its arg and uses it to check whether the key exists in GetStorage.

Just like SharedPreferences this method returns a bool, true or false:

myStorage.hasData('userId');
// true

In the above snippet, userId exists in the GetStorage. That’s why it returns true.

Delete Data

To remove data from the GetStorage, we’ll use the remove method. The key of the data is passed to the .remove(“key”) method so the key-value pair data in the GetStorage is deleted.

myStorage.remove("userId");

Here, the userId in the GetStorage is deleted. Also you can user .erase() method to clear all data in GetStorage.

Conclusion

So, which plugin to use for storing data locally in device, weather to use SharedPreferences OR GetStorage. by giving difference among them, the major difference is that SharedPreferences works asynchronously and on other hand GetStorage loads data on app start-up it works synchronously compared to SharedPreferences.

Lastly it generally depends on developer to choose a proper plugin which shits him best