SharedPreferences In Flutter

Introduction

 
SharedPreferences is one of the basic and most important aspects of any app development. Here, we will cover the basics of SharedPreferences, its methods, nature, where to use it, and how to use it.
 

Understanding

 
SharedPreferences is by nature persistent (permanent), i.e., it stores the data of that app so that the data remains in the memory even when you exit the app and open the app again. If you are from an Android or iOS native developer background, you should already be familiar with shared preferences and if you are from a web background, then you probably know about localstorage which is like shared_preferences in mobile development. Though localstorage vanishes when the browser history clears out but shared_preferences remain permanent.
 
Where
 
Let us take one scenario where we want to store some basic app settings like app language or any similar kind of thing. You can easily store that data in it. You can also use shared_preferences according to your requirement.
 
Note
Though shared_preferences claims a persistent nature, you need to keep in mind that storage disk will not guarantee for the data to be persistent. So don’t store important data in it.
 

Methods

 
Getter Methods
 
To retrieve data from shared_preferences
  1. bool getBool(String key)
  2. int getInt(String key)
  3. int getInt(String key)
  4. int getInt(String key)
  5. List<String> getStringList(String key)
  6. dynamic get(String key)
Setter Methods
 
To store data in shared_preferences
  1. Future < bool > setBool(String key, bool value)
  2. Future < bool > setInt(String key, int value)
  3. Future < bool > setDouble(String key, double value)
  4. Future < bool > setDouble(String key, double value)
  5. Future < bool > setDouble(String key, double value)
Delete Method
 
To delete data from shared_preferences
  1. Future < bool > remove(String key)

How to Use Shared_Preferences

 
Let us understand this with an example. The idea is to create a simple app in which we will set a language in shared_preferences for the app.
 
Step 1
 
Create a new Flutter app and remove everything from the main.dart file.
 
Step 2
 
Open the pubspec.yaml file and add a new dependency.
  1. shared_preferences: ^0.5.3+1  
Save the file and perform “flutter packages get” if you are not using Visual Studio Code.
 
Step 3
 
Import the following packages.
  1. import 'package:flutter/material.dart';  
  2. import 'package:shared_preferences/shared_preferences.dart';  
Step 4
 
Define the main method of app which is the entry point of the app.
  1. void main() {  
  2.  SharedPreferences.getInstance().then((prefs) {  
  3.    runApp(SharedPrefDemo(prefs: prefs));  
  4.  });  
  5. }  
We have initialized shared_preference before the app starts because we want the shared_preferences value throughout the app.
 
Step 5
 
Here, we are defining Stateful Widget because we want dynamic UI changes according to the changes in the app language.
  1. class SharedPrefDemo extends StatelessWidget {  
  2.  final SharedPreferences prefs;  
  3.  SharedPrefDemo({this.prefs});  
  4.  @override  
  5.  Widget build(BuildContext context) {  
  6.    return MaterialApp(  
  7.      title: 'SharedPreferences Demo',  
  8.      theme: ThemeData(  
  9.        primarySwatch: Colors.blue,  
  10.      ),  
  11.      home: AppSettingPage(prefs: prefs),  
  12.    );  
  13.  }  
  14. }  
  15.   
  16. class AppSettingPage extends StatefulWidget {  
  17.  final SharedPreferences prefs;  
  18.  AppSettingPage({this.prefs});  
  19.  @override  
  20.  _AppSettingPageState createState() => _AppSettingPageState();  
  21. }  
  22.   
  23. class _AppSettingPageState extends State<AppSettingPage> {  
  24.  List<LanguageTerms> terms = [];  
  25.  int selectedLanguage = 0;  
  26.  @override  
  27.  void initState() {  
  28.    terms = [  
  29.      LanguageTerms(  
  30.        termName: 'app_title',  
  31.        languages: ['App Name''एप का टाइटल'],  
  32.      ),  
  33.      LanguageTerms(  
  34.        termName: 'app_description',  
  35.        languages: ['App Description''एप का डिस्क्रिप्शन'],  
  36.      )  
  37.    ];  
  38.    if (widget.prefs.getInt('language') == null) {  
  39.      widget.prefs.setInt('language', 0);  
  40.    }  
  41.    selectedLanguage = widget.prefs.getInt('language');  
  42.    super.initState();  
  43.  }  
  44.   
  45.  @override  
  46.  Widget build(BuildContext context) {  
  47.    return Scaffold(  
  48.      appBar: AppBar(  
  49.        title: Text('${terms[0].languages[selectedLanguage]}'),  
  50.      ),  
  51.      body: Center(  
  52.        child: Column(  
  53.          mainAxisAlignment: MainAxisAlignment.center,  
  54.          children: <Widget>[  
  55.            Text(  
  56.              '${terms[1].languages[selectedLanguage]}',  
  57.            ),  
  58.            RaisedButton(  
  59.              child: Text('English'),  
  60.              onPressed: () {  
  61.                changeLaguage(0);  
  62.              },  
  63.            ),  
  64.            RaisedButton(  
  65.              child: Text('Hindi'),  
  66.              onPressed: () {  
  67.                changeLaguage(1);  
  68.              },  
  69.            ),  
  70.          ],  
  71.        ),  
  72.      ),  
  73.    );  
  74.  }  
  75.   
  76.  changeLaguage(index) {  
  77.    setState(() {  
  78.      selectedLanguage = index;  
  79.      widget.prefs.setInt('language', selectedLanguage);  
  80.    });  
  81.  }  
  82. }  
  83.   
  84. class LanguageTerms {  
  85.  String termName;  
  86.  List<String> languages;  
  87.  LanguageTerms({this.termName, this.languages});  
  88. }  
Step 6
 
Run the app in emulator/simulator or in the real device.
 
Step 7
 
After running the app, set your language and restart your app. You will see that the settings remain the same as you have selected just before closing the app.
 

Conclusion

 
Shared_Preferences is a crucial part of any app development and it is also easy to use and maintain.


Similar Articles