How to Save and Read Data from Shared Preferences in Flutter

Written by mohit | Published 2020/11/08
Tech Story Tags: flutter | flutter-for-mobile-app | flutter-app-development | flutter-tutorial | warmodroid | mobile-programming-flutter | mobile-app-development | mobile-apps

TLDR How to Save and Read Data from Shared Preferences in Flutter is a simple use case of shared preferences. 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. 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. You will find the same value in. the text field because of shared preferences. You can terminate the app and restart it again.via the TL;DR App

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.
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.
Let's 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.
Now you have to import this plugin in every file where you want to use it.
import 'package:shared_preferences/shared_preferences.dart';
Now you have the concept of writing and reading the data from local memory in Flutter, so let’s develop this app.
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);
  }
}
Conclusion
I hope this blog post is useful for you, do let me know your opinion in community.
This article is originally published at: warmodroid's blog

Written by mohit | https://www.warmodroid.xyz
Published by HackerNoon on 2020/11/08