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

Animated Navigation in Flutter

  Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.   Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition. Table of Contents Project Setup Code Result Project Setup Before directly applying to your existing project, practice the code in some example projects. For this tutorial, we are going to name our project screen_animation_tutorial. Open in VSCode or Android Studio. After that, we will make two Screens. The first Screen will be the Starting screen and the next Screen will be the Final Screen. So go ahead and create two dart files under the lib folder. The main.dart file code should look like this Dart import 'package:flutter/material.dart'; import 'package:screen_animation_tutorial/start_screen.dart'; void ...

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

Flutter : Image Picker Tutorial | Pick single image from Gallery

Introduction In this tutorial, we will create an image picker and display the content on the screen . I mage Picker picks a file from the Storage or Camera and stores it in an XFile object. Implementation Install dependency We will first need the image_picker dependency . To install it, add the following dependency to pubspec.yaml file. image_picker: ^0.8.4+3 Then click on Get Packages in your IDE or run the following command on your Terminal / Command Prompt. flutter pub get Example Import the dependency in your dart file. import 'package:image_picker/image_picker.dart' ; Syntax Image picking is a future task . So we need to await the image picking . Here is the syntax. await _picker.pickImage( source : ImageSource.gallery); Here we have provided the source from the gallery . We can also provide the source as a Camera using the following syntax. await _picker.pickImage( source : Ima...