Skip to main content

Flutter: SharedPreferences tutorial | How to setup SharedPreferences ?

Introduction

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.

Table of contents

  1. Approach
  2. Project setup
  3. Code
  4. Conclusion

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 .get() method.

Project setup

In the pubspec.yaml file, under the dependencies section add the following plugin.
shared_preferences: ^2.0.7
And then run 
flutter pub get 
in the command line or get packages if using any editor.

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 feature
    super.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:-
Starting App


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

Final


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 doubt, comment below. 






Comments

Popular posts from this blog

Flutter | Material Banner Tutorial

In this tutorial, we will create and display Material Banner in Flutter . Material Banners are displayed at the top of the screen . User interaction is required to dismiss the banner . Material Banner Material Banner alerts the user about action and p rovides some actions for the user to take . In brief, it alerts the user about an issue and the user address the issue . The user should dismiss the banner to remove it from the screen else it will be active. Syntax  ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: content, actions: actions)) Code Here is our starting class. It is a stateless class and we will display a banner when the Button is pressed. class SnackBarTutorial extends StatelessWidget { const SnackBarTutorial({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Material Banner"

How to create Snackbars in Flutter | Snackbar Tutorial

In this article, we will create and display different types of SnackBars in Flutter.  SnackBars in Flutter SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar . Syntax For creating a SnackBar, we use the following code. ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content)); Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button. Example Simple SnackBar class SnackBarTutorial extends StatelessWidget {   const SnackBarTutorial({Key? key}) : super (key: key);   @override   Widget build(BuildContext context) {     return

Flutter: DatePicker Tutorial both with Material and Cupertino Style

Introduction DatePicker is very important when you want the user to pick his / her date of birth or something else. In Flutter, implementing DatePicker is very easy and we will implement DatePicker in both Android or Material style and Cupertino or IOS style.  Table of contents Approach Project Setup Material Style DatePicker Cupertino Style DatePicker Conclusion Approach Flutter has widgets for everything and even for DatePicker. DatePicker widget is loaded with all needed animation and colours. So implementation is very easy.  Project Setup No extra plugins are required for this project and you can continue with your existing project. Here is the starting code. class DatePickerTutorial extends StatefulWidget { const DatePickerTutorial({Key? key}) : super (key: key); @ override _DatePickerTutorialState createState() => _DatePickerTutorialState(); } class _DatePickerTutorialState extends State<DatePick