Shared Preferences are a way of storing small information inside the application space. Storing small amounts of data within an application is a common requirement for modern apps. Whether it’s tracking user authentication, saving settings, or preserving user preferences, maintaining data between sessions is essential. Flutter provides a simple and efficient solution for this through Shared Preferences. Shared preferences are the key value that allows you to store and retrieve simple data types across sessions.
In this article, we are going to learn how to implement a custom class to store and access values stored in shared preferences.
Let’s understand the use of shared preferences with an example.
Example Case for Shared PreferencesSuppose you want to keep track of user authentication. You want to store the information about the user authentication status so that the user does not need to authenticate each time he opens the app. In this case, we can store authentication information like status, access token, and refresh token in the shared preferences and use them whenever we need across the application.
Steps to Implement Shared Preferences in FlutterIn this example, we are going to see how we can store different type of data in the shared preferences.
Step 1: Create and Setting Up the ProjectCreate a flutter project with the help of Android Studio or CLI.
flutter create flutter_sharedpref cd flutter_sharedpref Using this the flutter project will be created. The structure of the project is given below
Step 2: Adding Dependencies Add the shared_preferences package to your pubspec.yaml file
dependencies: flutter: sdk: flutter shared_preferences: ^2.0.6 after changing pubspec.yaml file, Run flutter pub get to install the dependencies.
Step 3 : Importing the packagein your dart file, import the following package to access its functionality
import 'package:shared_preferences/shared_preferences.dart'; Step 4: Saving DataLet’s save different types of data like int, double, String, Boolean, and list.
i). Saving Int Data in Shared Preferences
Dart
Future<void> addIntToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('intValue', 18);
}
ii). Saving Double Data in Shared Preferences
Dart
Future<void> addDoubleToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setDouble('doubleValue', 3.14159265359);
}
iii). Saving String Data in Shared Preferences
Dart
Future<void> addStringToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('stringValue', 'Hello, World!');
}
iv). Saving Boolean Data in Shared Preferences
Dart
Future<void> addBoolToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('boolValue', true);
}
v). Saving List Data in Shared Preferences
Dart
Future<void> addStringListToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('stringListValue', ['Hello', 'World']);
}
Step 5 : Reading Data
Reading data in share preferences is as easy as storing. we need key to pass to shared preferences to get the value of data stored.
i). Reading Int Data From Shared Preferences
Dart
Future<void> addIntToPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('intValue', 18);
}
ii). Reading Double Data From Shared Preferences
Dart
Future<double> readDoubleFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
double doubleValue = prefs.getDouble('doubleValue') ?? 0.0;
return doubleValue;
}
iii). Saving String Data in Shared Preferences
Dart
Future<String> readStringFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String stringValue = prefs.getString('stringValue') ?? '';
return stringValue;
}
iv). Reading Boolean Data From Shared Preferences
Dart
Future<bool> readBooleanFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool boolValue = prefs.getBool('isDataSaved') ?? false;
return boolValue;
}
v). Reading List From Shared Preferences
Dart
Future<bool> readListFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> listData = prefs.getStringList('stringListValue') ?? [];
return listData.isNotEmpty;
}
Note : As you can notice we have used null-aware operator. this will ensure that when the value from shared preferences is empty, the value on the right hand side of this operator gets assigned to variable.
Syntax
variable = expression1 ?? expression2; - variable => Is the variable that will be assigned the value.
- expression1 => Is the first expression, which is checked for null.
- expression2 => Is the second expression, which is the default value to be used if expression1 is null.
Creating Custom Shared Preferences ClassNow we have basic idea of how to implement shared preferences in flutter, Let’s see how can we make a custom class of shared preferences.
Step 1 : Creating a class Create a class and name it as per your need. in this case SharedPreferencesManager.
Dart
class SharedPreferencesManager {}
Step 2 : Declaring Keys for Shared PreferencesIn this step all you need to do is brainstorm your application idea and get the requirements for which data or values need to store in the shared preferences. accordingly you need to declare the keys, for example. In authentications scenario we might need to store user-id, access token, etc. so the keys would be the “user_id”, “access_token” .
Dart
final String intKey = "intValue";
final String doubleKey = "doubleValue";
final String stringKey = "stringValue";
final String boolKey = "boolValue";
final String listKey = "stringListValue";
Step 3 : Declare All the Required MethodsDeclaring the methods which will help store the shared preferences and retrieve them when method is called, All the methods which
Dart
/// Methods for writing data from shared preferences
Future<void> addIntToPref(intData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt(intKey, intData);
}
Future<void> addDoubleToPref(doubleData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setDouble(doubleKey, doubleData);
}
Future<void> addStringToPref(stringData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(stringKey, stringData);
}
Future<void> addBoolToPref(boolData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(boolKey, boolData);
}
Future<void> addStringListToPref(listData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList(listKey, listData);
}
/// Methods for reading data from shared preferences
Future<int> readIntFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getInt(intKey) ?? 0;
}
Future<double> readDoubleFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getDouble(doubleKey) ?? 0.0;
}
Future<String> readStringFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(stringKey) ?? '';
}
Future<bool> readBoolFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(boolKey) ?? false;
}
Future<List<String>> readListFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getStringList(listKey) ?? [];
}
as we can see we have declared methods to store shared preferences as well as read shared preferences. using the object of this class we can easily call the methods to read and write data.
Step 4 : Storing Data in Shared Preferences using Custom class Object
Next thing we need to do is create an object of “SharedPreferencesManager” class and use it to perform operations.
Dart
// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();
// Call the addIntToPref method and pass the integer value
prefManager.addIntToPref(10);
// Call the addDoubleToPref method and pass the double value
prefManager.addDoubleToPref(10.5);
// Call the addStringToPref method and pass the string value
prefManager.addStringToPref('Hello World');
// Call the addBoolToPref method and pass the boolean value
prefManager.addBoolToPref(true);
// Call the addStringListToPref method and pass the list of strings
prefManager.addStringListToPref(['One', 'Two', 'Three']);
Step 5 : Retrieving Data from Shared Preferences Using Custom class Object Similarly, we will now call the methods to read the data from shared preferences. we are assigning these values or data to variables hence we can use them later. for this we are making one method and inside it reading all the data.
Dart
bool isDataRead = false;
int intValue = 0;
double doubleValue = 0.0;
String stringValue = '';
bool boolValue = false;
List<String> stringListValue = [];
// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();
// Method to read data from shared preferences
void readData() async {
intValue = await prefManager.readIntFromPref();
doubleValue = await prefManager.readDoubleFromPref();
stringValue = await prefManager.readStringFromPref();
boolValue = await prefManager.readBoolFromPref();
stringListValue = await prefManager.readListFromPref();
}
as we can see , readData() method is used to read data by calling methods declared in custom class, and assigned values to declared variables.
Here is the whole functional code:
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_sharedpref/my_home_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Shared Preferences',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
my_home_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_sharedpref/read_data_screen.dart';
import 'package:flutter_sharedpref/util/shared_preferences_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isDataSaved = false;
// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
isDataSaved
? const Text('Data Saved!')
: const Text('Data Not Saved!'),
ElevatedButton(
onPressed: () {
// Call the addIntToPref method and pass the integer value
prefManager.addIntToPref(10);
// Call the addDoubleToPref method and pass the double value
prefManager.addDoubleToPref(10.5);
// Call the addStringToPref method and pass the string value
prefManager.addStringToPref('Hello World');
// Call the addBoolToPref method and pass the boolean value
prefManager.addBoolToPref(true);
// Call the addStringListToPref method and pass the list of strings
prefManager.addStringListToPref(['One', 'Two', 'Three']);
setState(() {
isDataSaved = true;
});
},
child: const Text('Save Data'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ReadDataScreen()),
);
},
child: const Text('Go to Next Screen'),
),
],
),
),
);
}
}
read_data_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_sharedpref/util/shared_preferences_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ReadDataScreen extends StatefulWidget {
const ReadDataScreen({super.key});
@override
State<ReadDataScreen> createState() => _ReadDataScreenState();
}
class _ReadDataScreenState extends State<ReadDataScreen> {
bool isDataRead = false;
int intValue = 0;
double doubleValue = 0.0;
String stringValue = '';
bool boolValue = false;
List<String> stringListValue = [];
// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();
// Method to read data from shared preferences
void readData() async {
intValue = await prefManager.readIntFromPref();
doubleValue = await prefManager.readDoubleFromPref();
stringValue = await prefManager.readStringFromPref();
boolValue = await prefManager.readBoolFromPref();
stringListValue = await prefManager.readListFromPref();
setState(() {
isDataRead = true;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Read Data'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
readData();
},
child: const Text('Read Data'),
),
const SizedBox(height: 20),
isDataRead
? Column(
children: [
Text('Int Value: $intValue'),
Text('Double Value: $doubleValue'),
Text('String Value: $stringValue'),
Text('Bool Value: $boolValue'),
Text('String List Value: $stringListValue'),
],
)
: const Text('Data Not Read!'),
],
),
),
);
}
}
shared_preferences_manger.dart
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesManager {
final String intKey = "intValue";
final String doubleKey = "doubleValue";
final String stringKey = "stringValue";
final String boolKey = "boolValue";
final String listKey = "stringListValue";
/// Methods for writing data from shared preferences
Future<void> addIntToPref(intData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt(intKey, intData);
}
Future<void> addDoubleToPref(doubleData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setDouble(doubleKey, doubleData);
}
Future<void> addStringToPref(stringData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(stringKey, stringData);
}
Future<void> addBoolToPref(boolData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(boolKey, boolData);
}
Future<void> addStringListToPref(listData) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList(listKey, listData);
}
/// Methods for reading data from shared preferences
Future<int> readIntFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getInt(intKey) ?? 0;
}
Future<double> readDoubleFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getDouble(doubleKey) ?? 0.0;
}
Future<String> readStringFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(stringKey) ?? '';
}
Future<bool> readBoolFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(boolKey) ?? false;
}
Future<List<String>> readListFromPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getStringList(listKey) ?? [];
}
}
OutputConclusion In this article we have learned how to create custom shared preferences class in flutter by implementing simple app which will store and retrieve some basic data. It used package called “shared_preferences”. we can use this method to build scalable applications which will be easy to manage and maintain.
|