Flutter shared preference
Introduction
In this blog I show you how to use Shared Preference in your flutter project, I am sure understood working of shared preference if still, you have any question in your mind then continue to read this blog your all doubts get resolve.
In mobile application development have functionality for storing the data, Shared Preference is also one of the ways for storing the data.
It has a key-value pair for storing and retrieve the data we can say that Shared Preference is similar to maps in the collection framework.
Shared preference doesn’t need any database for storing the data and also we don’t have need any query to retrieve the data from it. Shared Preference objects share common memory locations like static members so that we can store and retrieve the data from different objects.
Start
- Create a flutter project
- add dependency shared_preferences: <latest_version> in pubspec.yaml file
import
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences prefs;
void saveData(String data)async{ prefs=await SharedPreferences.getInstance(); prefs.setString("setString", "save string"); prefs.setBool("setBool", false); prefs.setDouble("setDouble", 20.5); prefs.setInt("setInt", 20); prefs.setStringList("setStringList", ['value1','value2','value3']); }
retrieveData() async { final sharedPreferences = await SharedPreferences.getInstance(); String getString = prefs.getString("setString"); bool getBool = prefs.getBool("setBool"); double getDouble = prefs.getDouble("setDouble"); int getInt = prefs.getInt("setInt"); List<String> getList = prefs.getStringList("setStringList"); }
void clear()async{ prefs=await SharedPreferences.getInstance(); prefs.clear(); }
Now you can simply call these functions as you need and use shared preference in your project.