Flutter: SharedPreferences tutorial | How to setup SharedPreferences ?

Manav SarkarManav Sarkar
4 min read

Data saving and storing is a common practice in applications. We have many options like SQL, NoSQL and SharedPreference. The first two options are mainly focused on large amounts of data with large transactions with constant efficiency. If you want only to store the user progress in terms of levels the user crossed or name and age of user or if the user wants to turn off or on the music of the application. Here comes the SharedPreferences data saving type.

So we will learn how to save data in our app using SharedPreference and then call the data.

Approach

We need to add the plugin for SharedPreference in our project. After that, we need to instantiate the SharedPreference object in our class. After that, if we need to save data we will call the .set() method and for retrieving we need to call the .get() method.
Project setup
In the pubspec.yaml file, under the dependencies section, import the following plugin.

shared_preferences: ^2.0.7

For this tutorial, we will create a project to save the name and age of the user. Here is the starting code. The code has two text fields for saving name and age and a button. In the code section, we will implement the saving feature and the retrieving feature in our app.

class SharedPrefTutorial extends StatefulWidget {
  const SharedPrefTutorial({Key? key}) : super(key: key);

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

class _SharedPrefTutorialState extends State<SharedPrefTutorial> {
  TextEditingController nameController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  @override
  void initState() {
    // TODO: retrieving featuresuper.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Shared Preference"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: nameController,
              keyboardType: TextInputType.name,
              decoration: InputDecoration(
                hintText: "Enter name",
                labelText: "Name",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: ageController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                hintText: "Enter age",
                labelText: "Age",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              //TODO Saving feature
            },
            child: Text("Save"),
          )
        ],
      ),
    );
  }
}

The starting code will look as follows:-

Code

Shared Preference Plugin

Shared Preference saves data in key and value format ( Map<key, value> ) and also retrieves value using the key format. We can save the value in the form of int, double, string and bool.

Implementation of Saving feature

We will implement the saving feature in the onPressed(){} function of the Button.

First, get the instance of SharedPreferences and store the value in the prefs variable. Also, add the async modifier onPressed function.

onPressed: () async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
},

Now when the button is pressed, we will set two string values, first the name and then the age.

We know that the age is an integer value but we are using TextEditingController which returns a string value.

We will call the setString(key, value) function to set the values.

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('name', nameController.text);
prefs.setString('age', ageController.text);

Implementation of Retrieving feature

We will create a function to get both name and age and then we will set the values respectively. The function will be called from the init function.

To get the values, we use the .getString( key ) function.

We will have to use the same key value as used in the time of saving the values. For the first time, it will be null, so we will set it as an empty string.

_retrieveValues() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    nameController.text = prefs.getString('name') ?? "";
    ageController.text = prefs.getString('age') ?? "";
  });
}

And the init function will be as follows.

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

Now run the app again.

We have implemented our code successfully and here is the full code.

class _SharedPrefTutorialState extends State<SharedPrefTutorial> {
  TextEditingController nameController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  _retrieveValues() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      nameController.text = prefs.getString('name') ?? "";
      ageController.text = prefs.getString('age') ?? "";
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Shared Preference"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: nameController,
              keyboardType: TextInputType.name,
              decoration: InputDecoration(
                hintText: "Enter name",
                labelText: "Name",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: ageController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                hintText: "Enter age",
                labelText: "Age",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              SharedPreferences prefs = await SharedPreferences.getInstance();
              prefs.setString('name', nameController.text);
              prefs.setString('age', ageController.text);
            },
            child: Text("Save"),
          )
        ],
      ),
    );
  }
}

Conclusion

We have learned to use the SharedPreferences and if you want to store the bool value or double or integer use the respective functions. Remember that it is not for any critical value and also not for large sets of data.

Hope you liked the tutorial. If you have any doubts, comment below.

0
Subscribe to my newsletter

Read articles from Manav Sarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manav Sarkar
Manav Sarkar