Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Using SharedPreferences to store data locally in Flutter

There comes a time where we might want to persist data in our Flutter app so we can re-use them anytime the user launches our app. The app can be able to remember the data even after the activity has been killed off, this is possible through the use of SharedPreferences.

In this article, we will learn about how to use the SharedPrefences in our Flutter app, we will learn to persist and modify data in it.

Read on.

SharedPreferences

SharedPreferemces is what has been used in Android and iOS to store simple data in the app's allocated space. This data exists even when the app is killed off and starts all over again, we can still retrieve the value as it was.

These data stored in SharedPreferences can be edited and also deleted. The SharedPreferences stores the data in a key-value pair.

To use SharedPreferneces in flutter there is a plugin called shared_preferences built by flutter.dev that enables us to store data. The plugin wraps NSUserDefaults on iOS and SharedPreferences on Android.

Warning: SharedPrefernece should be used to store critical data like passwords, tokens, and all or complex relational data.

In the below sections, we will learn how to scaffold a Flutter project, add the shared_preferences plugin to a Flutter project, and the methods exposed to us by the plugin.

Scaffold Flutter project

We will need to have some tools and binaries already installed in our machine.

Requirements

Flutter

We will have to install the Flutter SDK on our machine. To do that, you need to choose your Flutter binary as per your machine below:

After the installation, we will have the flutter CLI available globally in our system. We can run the below command to test this:

➜  flutter --version

Flutter 2.0.6 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 1d9032c7e1 (3 months ago) • 2021-04-29 17:37:58 -0700
Engine • revision 05e680e202
Tools • Dart 2.12.3

Your version may be different from mine but we have verified that Flutter SDK was successfully installed.

Android Studio

We will be developing for the Android OS and also we will need an emulator to test our apps on the run, so that's why we will need to install this software. Android Studio is the official IDE/SDK used in building, testing, and publishing Android apps.

Go to https://developer.android.com/studio to download and install Android Studio on your machine.

If you want to use Android Studio to develop Flutter projects you will need to install the below plugins:

We scaffold a Flutter project. To do that we run the command, flutter create shared_pref. This command will create a folder shared_pref and create a Flutter project inside it. You can open the project using VS Code or Android Studio.

Install the shared_preferences

Now, we have Flutter SDK ready and set, we will now install the shared_preferences plugin.

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

dependencies:
  flutter:
    sdk: flutter
  shared_preferences:

This will install the latest version of the dependency.

Import the shared_preferences

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

import 'package:shared_preferences/shared_preferences.dart';

Initializing shared_preferences

The shared_preferences plugin exports a SharedPreferences class, it has methods that can be used to set data of different primitive types in SharedPreferences. It has a method getInstance, this method 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.

shared_preferences methods

Let's see how we can add data to the SharedPreferences, how we can get data, edit and delete data from SharedPrefernces.

Add data

We can add data of different primitive types to SharedPreferences. We can add these primitive types:

  • int
  • string
  • bool
  • double

Each primitive type has its corresponding setter method that does the job.

Note: The key of the key-value pair is in string.

Add int

prefs.setInt('counter', 1);

This adds an int, 1 to the counter table of SharedPreferences.

Add string

prefs.setString('counter', "yes");

This adds a string "yes" to counter.

Add bool

prefs.setBool('counter', true);

This adds a bool, true to the counter.

Add double

prefs.setDouble('counter', 10.2);

This adds a double value, 10.2 to the counter.

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

Get int data

int value = prefs.getInt('counter');

The getInt method is used to retrieve an int value from the SharedPreferences.

value // 1

Get bool data

bool value = prefs.getBool('counter');

This method getBool returns a boolean value from the SharedPreferences.

value // true

Get double data

double value = prefs.getDouble('counter');

This method getDouble returns a double value from the SharedPreferences.

value // 10.2

Get string data

string value = prefs.getString('counter');

This method getString returns a string value from the SharedPreferences.

value // "yes"

null value

In a case where the data is not present in the SharedPreferences, a null value is returned.

prefs.getInt("_counter")
// null

prefs.getBool("_counter")
// null

prefs.getString("_counter")
// null

prefs.getDouble("_counter")
// null

Deleting data

To remove data from the SharedPreferences we will use the remove method. The key of the data is passed to the .remove method so the key-value pair data in the SharedPreferences is deleted.

prefs.remove("counter");

Here, the counter in the SharedPreferences is deleted.

Checking if data exists

We can check in SharedPreferences to see if a data exists before we can either read or write. To do this we use the containsKey method. The method accepts the key of the data in its arg, this key will be used by containsKey method to check if the key exists in SharedPreferences.

The method returns a bool, true or false.

prefs.containsKey("counter")
// true

In the above, counter exists in the SharedPreferences that's why true was returned.

prefs.containsKey("_counter")
// false

_counter does not exist so that's why false was returned.

Using shared_preferences

By default, Flutter adds a counter project whenever we scaffold a Flutter project. This counter project enables us to increment a counter when a FloatingActionButton is pressed. The current state of the counter is displayed as it is being increased.

See the code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Now, this counter reverts to 0 when the app is destroyed or closed. We will use SharedPreferneces to persist the state of the counter so the counter value begins from where it was before the app was killed off.

Let's do it.

First, we will import the shared_preferences plugin.

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

Then, we added a initState lifecycle method in the MyHomePageState widget. This lifecycle method is called when a stateful widget is being initialized. Here, we will load the counter from SharedPreferences, if present we make it the counter value, if not we assign 0 to the counter:

  void loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0);
    });
  }

  @override
  void initState() {
    super.initState();
    loadCounter();
  }

Now, in the _incrementCounter function we will make it an async function. Inside it, we will get the counter from SharedPreferences increment it, then we set the counter with the increment and set the increment also in the SharedPreferences. See the code:

  void _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = ((prefs.getInt('counter') ?? 0) + 1);
      prefs.setInt('counter', _counter);
    });
  }

Now, our Flutter application can remember the last value of the counter when destroyed and restarted.

Test app

start app

increment to 7

Kill app

Restart app

Conclusion

We learned about SharedPreferences here. We started by learning what SharedPreferences is and how it is being used in Android and iOS. Later down we introduced the shared_preferences plugin and we learned how to set up Flutter in our machine.

Next, we learned how to import the shared_preferences plugin, how to initialize its instance, its methods, and what all of them do. We modified the normal Flutter counter project to show how we can use the shared_preferences plugin to persist the counter value and retrieve it after the app has been killed and restarted.

The shared_preferences plugin is absolutely very helpful in Flutter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment