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
- bool getBool(String key)
- int getInt(String key)
- int getInt(String key)
- int getInt(String key)
- List<String> getStringList(String key)
- dynamic get(String key)
Setter Methods
To store data in shared_preferences
- Future < bool > setBool(String key, bool value)
- Future < bool > setInt(String key, int value)
- Future < bool > setDouble(String key, double value)
- Future < bool > setDouble(String key, double value)
- Future < bool > setDouble(String key, double value)
Delete Method
To delete data from shared_preferences
-
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.
- 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.
- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
Step 4
Define the main method of app which is the entry point of the app.
- void main() {
- SharedPreferences.getInstance().then((prefs) {
- runApp(SharedPrefDemo(prefs: prefs));
- });
- }
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.
- class SharedPrefDemo extends StatelessWidget {
- final SharedPreferences prefs;
- SharedPrefDemo({this.prefs});
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'SharedPreferences Demo',
- theme: ThemeData(
- primarySwatch: Colors.blue,
- ),
- home: AppSettingPage(prefs: prefs),
- );
- }
- }
-
- class AppSettingPage extends StatefulWidget {
- final SharedPreferences prefs;
- AppSettingPage({this.prefs});
- @override
- _AppSettingPageState createState() => _AppSettingPageState();
- }
-
- class _AppSettingPageState extends State<AppSettingPage> {
- List<LanguageTerms> terms = [];
- int selectedLanguage = 0;
- @override
- void initState() {
- terms = [
- LanguageTerms(
- termName: 'app_title',
- languages: ['App Name', 'एप का टाइटल'],
- ),
- LanguageTerms(
- termName: 'app_description',
- languages: ['App Description', 'एप का डिस्क्रिप्शन'],
- )
- ];
- if (widget.prefs.getInt('language') == null) {
- widget.prefs.setInt('language', 0);
- }
- selectedLanguage = widget.prefs.getInt('language');
- super.initState();
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('${terms[0].languages[selectedLanguage]}'),
- ),
- body: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Text(
- '${terms[1].languages[selectedLanguage]}',
- ),
- RaisedButton(
- child: Text('English'),
- onPressed: () {
- changeLaguage(0);
- },
- ),
- RaisedButton(
- child: Text('Hindi'),
- onPressed: () {
- changeLaguage(1);
- },
- ),
- ],
- ),
- ),
- );
- }
-
- changeLaguage(index) {
- setState(() {
- selectedLanguage = index;
- widget.prefs.setInt('language', selectedLanguage);
- });
- }
- }
-
- class LanguageTerms {
- String termName;
- List<String> languages;
- LanguageTerms({this.termName, this.languages});
- }
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.