September 22, 2020

Saving and reading data from shared preferences in Flutter

By Mohit Agrawal

Save data locally in Flutter using shared preferences

Introduction

Shared preferences are used to store the small amount of data like some int, double, bool or string value in the local memory. Let me take a simple use case of it for your better understanding.

Keep the user logged in using shared preferences

This is one of the best use cases of shared preferences. Once the user gives the correct id and password then we save a bool value equal to true in local memory. Let’s say isUserLoggedIn = true.

Now you can check the value of isUserLoggedIn whenever the user starts the app and based on the value you can show the login screen or main dashboard directly.

What we are going to build?

To demonstrate the use of shared preferences in Flutter we will develop a simple app in which you can increase or decrease the number shown in the text filed with the help of these two buttons.

Once you set the desired value then you can terminate the app and restart it again. You will find the same value in the text field because of shared preferences.

shared preferences flutter 1

Implementation

Lets get started with the coding part!!! 😀

Create a new Flutter project

Create a new Flutter project using the android studio. You can use your existing project also if you have any.

Get the plugin

We will be using this plugin for implementing Shared Preferences. It is the wrapper of SharedPreferences in android and UserDefaults in iOS.

Go to the pubspec.yaml and paste the dependency like this.

shared preferences flutter 2

Now you have to import this plugin in every file where you want to use it.

import 'package:shared_preferences/shared_preferences.dart';

How to read and write the data in persistent memory?

Before that, you should know what all types of data can be saved. You can save only Int, Double, Bool, String and List type of data.

Let’s see all of them one by one.

First, need to create a object of shared preference class like this.

final prefs = await SharedPreferences.getInstance();

Int

// read
final myInt = prefs.getInt('my_int_key') ?? 0;
// write
prefs.setInt('my_int_key', 30);

double

// read
final myDouble = prefs.getDouble('my_double_key') ?? 0.0;
// write
prefs.setDouble('my_double_key', 30.0);

string

// read
final myString = prefs.getString('my_string_key') ?? '';
// write
prefs.setString('my_string_key', 'Warmodroid');

bool

// read
final myBool = prefs.getBool('my_bool_key') ?? false;
// write
prefs.setBool('my_bool_key', true);

string list

// read
final myStringList = prefs.getStringList('string_list_key') ?? [];
// write
prefs.setStringList('string_list_key', ['one', 'two', 'three']);

Time to use the above concept 😎

Now you have the concept of writing and reading the data from local memory in Flutter, so let’s develop this app.

shared preferences flutter 1

Here I am not talking about the UI part because our main focus is on the logic. The integer value in the text field is coming from the saved preferences.

When you click on the plus button, I am just increasing the current integer value by 1 and saving the new value in the memory.

RaisedButton(onPressed: () {
              setState(() {
                number++;
              });
              saveIntInLocalMemory('COUNTER_NUMBER', number);
            },
            child: Text('+'),
            )

Similarly, when you are pressing the minus button, I am decreasing the current integer value by 1 and saving the new value to the memory.

RaisedButton(onPressed: (){
              setState(() {
                number--;
              });
              saveIntInLocalMemory('COUNTER_NUMBER', number);
            },
            child: Text('-'),
            )

Complete Source code

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.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,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var number = 0;

  @override
  void initState() {
    super.initState();
    getIntFromLocalMemory('COUNTER_NUMBER').then((value) =>
      number = value
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Save data locally'),
      ),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(onPressed: (){
              setState(() {
                number--;
              });
              saveIntInLocalMemory('COUNTER_NUMBER', number);
            },
            child: Text('-'),
            ),
            Padding(
              padding: const EdgeInsets.all(21.0),
              child: Text(number.toString()),
            ),
            RaisedButton(onPressed: () {
              setState(() {
                number++;
              });
              saveIntInLocalMemory('COUNTER_NUMBER', number);
            },
            child: Text('+'),
            )
          ],
        ),
      )
    );
  }

  /*
  * It saves the int value to the local memory.
  * */
  Future<int> getIntFromLocalMemory(String key) async {
    var pref = await SharedPreferences.getInstance();
    var number = pref.getInt(key) ?? 0;
    return number;
  }

  /*
  * It returns the saved the int value from the memory.
  * */
  Future<void> saveIntInLocalMemory(String key, int value) async {
    var pref = await SharedPreferences.getInstance();
    pref.setInt(key, value);
  }
}

Now you can run this complete code and play with it. If you are facing any issue then please let me know it in comment section.

Demo

Frequently asked question on shared preferences

  1. What is the memory limit in shared preferences?

    As such, there is no limit defined for storing data in the shared preferences. But I will recommend you not to store any big amount of data. If you really want to store some huge data then go with the SQLite database.

  2. Shared preferences VS SQLite

    In short shared preferences are used to store only a small amount of data and you can not make any query on it.
    But SQLite is designed to store huge amount of data and you can run queries on it

Conclusion

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!