SharedPreferences in Flutter

SharedPreferences is use for stores data key-value pair . SharedPreferences in flutter uses NSUserDefaultson iOS and SharedPreferences on Android, providing a persistent store for simple data.

Suppose you want to save a small value that you want to refer to later in application.

We do not use SQLite to store small values ​​because we need to define classed for SQLite.

Implementation

Add library to .yaml file under dependencies

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<latest version>"

package import

import 'package:shared_preferences/shared_preferences.dart';

Store data ( intStringdouble and bool  )

Store String value

addStringToSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('keyValueString', "test");
}

Store int value

addIntToSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setInt('keyValueInt', 1000);
}

Store double value

addDoubleToSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setDouble('keyValueDouble', 99.99);
}

Store boolean value

addBoolToSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool('keyValueBool', true);
}

Retrieve data

When we are reading the data from the storage through SharedPreferences we only required to pass the key only.

getStringValuesSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  String stringValue = prefs.getString('keyValueString');
  return stringValue;
}
getIntValuesSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  
  int intValue = prefs.getInt('keyValueInt');
  return intValue;
}
getDoubleValuesSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
 
  double doubleValue = prefs.getDouble('keyValueDouble');
  return doubleValue;
}
getBoolValuesSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
 
  bool boolValue = prefs.getBool('keyValueBool');
  return boolValue;
}

Remove data

To remove the data from the storage

removeValues() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  //Remove String
  prefs.remove("keyValueString");
  //Remove int
  prefs.remove("keyValueInt");
  //Remove double
  prefs.remove("keyValueDouble");
  //Remove bool
  prefs.remove("keyValueBool");
}

Leave a Reply

Your email address will not be published.