Shared Preferences in Flutter
- Save data in localStorage from user input
- Read/Retrieve data from localStorage
- Delete data from localStorage
home: LocalStorageData()
In Pubspec.yaml file:-
We add dependency of SharedPreferences:-
shared_preferences: 2.0.8
TextEditingController controller = TextEditingController();
Create variable of type TextEditingController to use the data input by user into the text field.
late SharedPreferences prefs;
Declare variable of SharedPreferences named prefs which will be used to open SharedPreferences
String name = " ";
Creating String variable to show data from SharedPreferences to UI/Screen
we Created 3 buttons and 1 textfield and i assuming that you already know how to create them So In every Button when pressed i.e. onPressed function of Buttons we are going to call method which i am show why we have to create them in deeply.
save() async {
prefs = await SharedPreferences.getInstance();
prefs.setString('text', controller.text.toString());
}
At above its called Save() function which is used to save the data(user input data from textfield) into SharedPreferences
using key: value format i.e. the data will be saved into the local by the name 'text' here using setString method and we
have to call getInstance method to get into SharedPreferences and here we used await because It maybe take some time
to get or save data in or from local so we want success and we can wait for some mili seconds to complete that part.
retrieve() async {
prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString('text')!;
});
}
Everything is same as save() function but with few little changes which are
- Here we are looking to read data so we used getString method and our data is saved
- in key: value pair so i am calling key here
- and i am using setState so that the UI will be changed i.e. the data from shared
- preferences will be shown in the screen and for that we have to use setState.
delete() async {
prefs = await SharedPreferences.getInstance();
prefs.remove('text');
name = "";
setState(() {});
}
Everything is same as above other 2 function but here i am going to delete data from SharedPreferences
so just use remove() function and delete using key of that data.