Flutter - SharedPreferences
Last Updated :
24 Apr, 2023
SharedPreference is a small data storage in our phone where we can store data in pairs of keys and values. We can store an integer, string, list of strings, Boolean, and double in SharedPreferences. Now let us discuss where we can implement these. The first is to save the user information user is logged in or not, any id or some basic user details so that users don’t have to log in again whenever a user opens that app.
shared_preferences Library in Flutter
1. Add Package to the pubspec.yaml file. Refer to this article: How to Setup SharedPreferences in Flutter
2. Define Strings in a constant file to set and get value at that particular key (This step is not mandatory, you can skip it and can directly add where you need it).
const String key="myKey";
3. Firstly, you need to create an instance of shared preference and store it in a variable.
final prefs = await SharedPreferences.getInstance();
4. Using prefs, you can access many functions to set and get data in different data types.
E.g. prefs.getBool(key), prefs.getInt(key) ,etc.
5. Key must be the same in both getter and setter to get value for that particular key. like below
5. 1. Bool DataType
Getter:- prefs.getBool(key) ?? false,
Setter:- prefs.setBool(key, value)
Value — true,false
Code:
const boolSharedPreference = "bool shared preferences";
static Future getBool() async {
final prefs = await SharedPreferences.getInstance();
prefs.setBool(boolSharedPreference, true);
}
static Future<bool> setBool() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(boolSharedPreference) ?? false;
}
5. 2. Int DataType
Getter:- prefs.getInt(key) ?? 0,
Setter:- prefs.setInt(key, value)
value -integer value 1,4566,8423235,
Code:
const intSharedPreference = "integer shared preferences";
static Future setInt() async {
final prefs = await SharedPreferences.getInstance();
return prefs.setInt(intSharedPreference, 1);
}
static Future<int> getInt() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt(intSharedPreference) ?? 0;
}
5. 3. Double DataType
Getter:- prefs.getDouble(key) ?? 0.0,
Setter:- prefs.setDouble(key, value)
value any double value like 2.0,6.7,12344.8
Code:
const doubleSharedPreference = "double shared preferences";
static Future setDouble() async {
final prefs = await SharedPreferences.getInstance();
return prefs.setDouble(doubleSharedPreference, 0.0);
}
static Future<double> getDouble() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getDouble(doubleSharedPreference) ?? 0.0;
}
5. 4. String DataType
Getter:- prefs.getString(key) ?? “”,
Setter:- prefs.setString(key, value)
Value -this can be anything under invertedComma .
Code:
const stringSharedPreference = "string shared preferences";
static Future<String> getString() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(listSharedPreference) ?? "";
}
static Future setString() async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(stringSharedPreference, "");
}
5. 5. List of String DataType
Getter:- prefs.getStringList(key) ?? [],
Setter:- prefs.setStringList(key, value)
Value -List of strings (anything under inverted comma)
Code:
const listSharedPreference = "list shared preferences";
static Future setListString(
{required String id, required String token}) async {
final prefs = await SharedPreferences.getInstance();
prefs.setStringList(listSharedPreference, [id, token]);
}
static Future<List<String>> getListString() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(listSharedPreference) ?? [];
}
5. 6. Json or Map Data Type
Getter:- json.decode(prefs.getString(key).toString()),
Setter:- prefs.setString(key, jsonEncode(value))
to use its value.
// Map myData= jsonDecode(value);
value :- {“name”:”risheeta”,
“experience”:1.5,
“age”:21,
“skills”:[“flutter”,”Html”]}
Code:
const mapSharedPreference = "map shared preferences";
static Future setMap() async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(
mapSharedPreference,
jsonEncode({
"name": "",
}));
}
static Future<Map> getMap() async {
final prefs = await SharedPreferences.getInstance();
return jsonDecode(prefs.getString(mapSharedPreference) ?? "") ?? {};
}
This function will clear complete shared preferences means it will delete all key-value pairs stored in the memory. You can clean this memory with this function. You can clear this by uninstalling the app and reinstalling it or cleaning the data of that particular application.
Code:
static Future clearSharedPref() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
Dart
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_flutter/constants/value.dart';
class SharedPref {
static Future setBool() async {
final prefs = await SharedPreferences.getInstance();
prefs.setBool(boolSharedPreference, true);
}
static Future<bool> getBool(bool value) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(boolSharedPreference) ?? false;
}
static Future setListString(
{required String id, required String token}) async {
final prefs = await SharedPreferences.getInstance();
prefs.setStringList(listSharedPreference, [id, token]);
}
static Future<List<String>> getListString() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(listSharedPreference) ?? [];
}
static Future<String> getString() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(listSharedPreference) ?? "";
}
static Future setString(String value) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(stringSharedPreference, value);
}
static Future setInt(int val) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setInt(intSharedPreference, val);
}
static Future<int> getInt() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt(intSharedPreference) ?? 0;
}
static Future setDouble(double val) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setDouble(doubleSharedPreference, val);
}
static Future<double> getDouble() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getDouble(doubleSharedPreference) ?? 0.0;
}
static Future setMap(Map value) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(mapSharedPreference, jsonEncode(value));
}
static Future<Map> getMap() async {
final prefs = await SharedPreferences.getInstance();
return jsonDecode(prefs.getString(mapSharedPreference) ?? "") ?? {};
}
static Future clearSharedPref() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
How to use this function?
For Example, we want to getInt value
1. To get Value
SharedPref.getInt().then((value) {
print(value);
// value will be your data stored in that key
});
2. To Set value
SharedPref.setInt(1);
Dart
const intSharedPreference = "integer shared preferences";
const doubleSharedPreference = "double shared preferences";
const stringSharedPreference = "string shared preferences";
const mapSharedPreference = "map shared preferences";
const listSharedPreference = "list shared preferences";
const boolSharedPreference = "bool shared preferences";
More Tips
You can store more than one key-value pair with the same data type, but it must have a different key. If you set 2 values with the same value of keys, it will overwrite that.
For Example:
We have set my mobile number in a key named customer data.
prefs.setString(customerData, 1234567890)
then somewhere else I set my age in the same key
prefs.setInt(customerData, 21)
Error Conditions
Error 1: Unhandled Exception: type ‘First Data type’ is not a subtype of type ‘Second Data Type’ in typecast.prefs.getString(customerData); it will give you 1234567890. but prefs.getInt(customerData) ;it will give you error like this. You can set many key-value pairs in shared preferences. But keys name must be unique in every pair. To access the value which you set already. You have to use the same key to get that value again from shared preferences.
Solution: Trying to change the data type.
Error 2: Unhandled exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Solution: Uninstall the application and reinstall it.
Error 3: MissingPluginException(No implementation found for method launch on channel plugins.flutter.io/url_launcher)
Solution: Flutter clean or rerun the project.
Similar Reads
How to Setup SharedPreferences in Flutter?
SharedPreferences is a package that enables the Application to store a small amount of data in your local storage. Like user name, id, etc. You don't need other databases for it like SQLITE, FIREBASE, etc. So in this article, we will see How to install the Shared Preferences package in Dart/Flutter
1 min read
Shared Preferences in Flutter
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 se
10 min read
Read and Write Data in Flutter using SharedPreferences
SharedPreferences is the best option to store a small amount of data in flutter projects. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, integer, float, Boolean that make up your pre
6 min read
Semantics flutter
Flutter, Googleâs UI toolkit for building specially compiled applications, provides powerful tools for creating beautiful and functional applications. Economics stands out as a key factor in the inclusive and accessible use of these tools. In this article, weâll explore what Semantics is, why itâs i
4 min read
Flutter - Themes
Themes are an integral part of UI for any application. Themes are used to design the fonts and colors of an application to make it more presentable. In Flutter, the Theme widget is used to add themes to an application. One can use it either for a particular part of the application like buttons and n
3 min read
Flutter - Named Routes
An app has to display multiple screens depending upon the user's needs. A user needs to back and forth from the multiple screens to the home screen. In, Flutter this is done with the help of Navigator.Note: In Flutter, screens and pages are called routes. Steps to Implement Named Routes in FlutterSt
3 min read
How to Install Shared Preferences in Flutter?
Shared preferences in flutter applications are used to store data in Local Storage. Shared Preferences store the data in a key-value pair. and we can also get data in a key-value pair using inbuilt functions. We can save large data in local storage or our Phone storage with the help of SQLite databa
2 min read
Flutter - OnBoarding Screen
Onboarding Screen is one of the most popular that you can see in most of the apps after loading of Splash Screen. The Onboarding Screen gives a short overview of an app. The onboarding Screen consists of three to four layouts which slide as we click on Next. In this article, we are going to see how
7 min read
Flutter- Screenshot Package
Flutter is a popular framework by Google which is growing fast with its growing community. The Flutter has created a buzz through its libraries, making the development fast-paced. Nowadays, everyone loves to take screenshots. If your application involves the use of screenshots, Flutter got a package
8 min read
Placeholder Flutter
Placeholder is a popular, inbuilt widget of the Flutter framework which creates an empty canvas/container on the screen to put content into, just like its name implies. It is analogous to both the placeholder attribute and the <div> tag of HTML. Almost all Flutter developers have reported usin
3 min read