SharedPreferences in Flutter

Avneesh Kumar
Nybles
Published in
4 min readJun 30, 2020
Shared Preferences in flutter

Hello, Today I take this opportunity to brief you on SharedPreferecnes used in Flutter.

What is SharedPreferences?

Shared Preferences is a Flutter package that enables Flutter Developers to create Apps that have persistence of data. Shared Preferences stores data in the form of [key] [value] pair on disk. It is recommended to use SharedPreferences when the amount of data is less.

For example — It can be used to store choices of the user, to store HighScore in a game, to store Login Credentials.

Is there any alternative to it?

Yes, there are a few alternatives to it. Basically in Flutter provides three ways to store data persistently.

  1. Using SharedPreferences
  2. Using SQLite — Implementation of this requires more complex codebase. It is used when we need to store a large amount of data relationally.
  3. Using Read and Write Files — Similar to file-handling, mostly data is stored in the form of Strings in .txt files.

How to use SharedPreference?

Well, we will learn this by creating a simple app that stores the number of taps on a button. So, before moving further create a new Flutter Project named ‘Demo’. Once the project is ready, follow these👇 simple steps.

Step 1 — Create UI

In this step, we create a UI for our app in main.dart file. Copy below code in your main.dart.

Step 2 — Adding Dependency

To use SharedPreferences in your app, we require the Flutter Package🎁 of it. So visit pub.dev. Search for SharedPreferences. Select the top package. and goto the installing tab, and copy

shared_preferences: <version_number>

Now in your project open pubspec.yaml and paste under dependencies.

paste in pubspec.yaml

Run

flutter pub get

Woohoo, you successfully added dependency.

Before moving ahead let us take a sneak peek of functions available in package

getInstance() — Loads and parses the [SharedPreferences] for the app from local disk.

getBool(String key) — Reads a bool from persistent storage with respect to [key].

Similarly, getString(String key), getInt(String key), and getDouble(String key) reads the value from persistent storage forgiven [key] and throws an exception if it is the not correct return type.

setInt(String key, int value) — Writes Int [value] to persistent storage for particular [key].

Similarly setString, setDouble, and setBool write [value] to persistent storage for given [key].

clear() — removes all the [key] [value] pairs from persistent storage.

Step 3 — Create a shared_preferences_helper.dart

Just copy paste below code.

Step 4 — Importing shared_preferences_helper.dart

We need to import shared_preferences_helper.dart to our main.dart.

Add below line at the top of our main.dart

import ‘shared_preferences_helper.dart’;

Step 5 — Complete main.dart

Add below code inside initState() function.

counter = SharedPreferencesHelper.getIntegerValue('counter');

Add below code inside onPressed() function of Reset IconButton.

SharedPreferencesHelper.clearPreferences();setState(() {counter = SharedPreferencesHelper.getIntegerValue('counter');});

Replace

FutureBuilder(builder: null, future: counter)

with code below

FutureBuilder( future: counter, 
builder:(BuildContext context, AsyncSnapshot<int> snapshot)
{
if (snapshot.hasError)
{
return Text('Error: ${snapshot.error}');
}
else
{
return Text('Button tapped ${snapshot.data}time${snapshot.data == 1 ? '' : 's'}');
}
}
)

at last Replace onPressed() function of FloatingActionButton with below code

onPressed: () async 
{
// fetches current value of counter
int lastValue = await SharedPreferencesHelper.getIntegerValue(
'counter');
// increaments latest value by 1
lastValue++;
// pushes updated value of counter to SharedPreferences
await SharedPreferencesHelper.setIntegerValue('counter', lastValue);
// updates State of App
setState(()
{
counter = SharedPreferencesHelper.getIntegerValue('counter');
});
},

Your final main.dart will look like👇 this.

Now run the App.

Final App

You can see that on completely closing app still, it retains the Number of taps on a Button. App uses SharedPreferences to achieve this.

Congratulations🎉! We have successfully created an App that uses shared preferences to store data persistently.

For more details on SharedPreferences visit the following resources:

Flutter Cookbook

Pub.dev

Find the complete project on GitHub here

About me —

Hello, I am Avneesh Kumar, UnderGrad at IIIT Allahabad, and Member App Development Wing GeekHaven.

If you liked this article, hit that clap button👏. It means a lot to me.

--

--

Avneesh Kumar
Nybles
Writer for

UnderGrad at IIIT Allahabad. Student Android Developer