Shared Preference in A Flutter

Or User Defaults In Flutter

Tony Wilson jesuraj
IVYMobility TechBytes
3 min readSep 14, 2020

--

Basically What is Shared Preference?. Just to save the users small size data in App, Like some kind of settings and some Data (Not too much, If much then need to go with some DataBase).

In flutter Shared Preferences are stored in XML format. And it supports in both iOS and Android.

Points to Note

  • Shared Preference is to save users small data in App.
  • Shared Preference data will lose its data while uninstalling App or while clearing Application Data.
  • Don't use Shared Preference as DataBase.

How To implement Shared Preference

Step-1: Adding dependencies for Shared Preference

Add the package at pubspec.yaml file.

Step-2: Importing Shared Preference

Yes you can save Int, String, Bool, List and Double in Shared preference.

set keyword is used to save the data in Shared preference. Setter as two parameters, key and value.

Key: Used while retrieving, it's like variable and it only can be in String format.

Value: The value you need to save.

prefs is variable here.

async stands for Asynchronous, Asynchronous operations let your program complete work while waiting for another operation to finish.

like

  • Fetching data over a network.
  • Writing to a database.
  • Reading data from a file.

setInt because we storing Int in shared preferences. If want to store String setStringis used.

'intValue' is key here.

Example for string :

setList , setDouble , setBool for list, double, bool.

Read Data

Here we need to pass only key to read data.

get is used for reading data from sharedPreferences.

Hope you got it, same for int and bool .

Removing from SharedPreferences

.remove and keyValue is used to remove.

Example:

To Check value is present or not?

containsKey used to check value is present or not.

containsKey will give an bool value, true for present and false for not present.

--

--