Open In App

Flutter – SharedPreferences

Improve
Improve
Like Article
Like
Save
Share
Report

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.



Last Updated : 24 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads