close

How To Store And Get Data From Shared Preferences in Flutter

Hello Guys How are you all? Hope you all are fine. Today We are going to learn How To Store And Get Data From Shared Preferences in Flutter?

We have to store some offline data to our storage and get them back while we want in shared preferences in flutter. In This tutorial very simple way I am going to explain How To Store And Get Data From Shared Preferences in Flutter. So lets start this tutorial.

How To Store And Get Data From Shared Preferences in Flutter

How To Store And Get Data From Shared Preferences in Flutter

Question: How To Store And Get Data From Shared Preferences in Flutter ?
Answer: How To Store And Get Data From Shared Preferences in Flutter. We have to store some offline data to our storage and get them back while we want in shared…

  • We are going to use flutter package for shared preferences.
  • define shared_preferences package in pubspec.yaml file.
  • Then make StorageUtil.dart file in your lib folder.
  • Then after import shared_preference package in our file.
  • Make class named StorageUtil in StorageUtil.dart file.
  • After that, define StorageUtil and SharedPreferences variables.
  • Actually Shared Preference is using async and await method. so it will use Future to put and get from Shared preference.
  • Make getInstance method to get Storage and set this method to init so it will init every time.
  • Then I Have Created Method to put data into Preference. so you can use this method.
  • I have also created method to get data from Preference.
  • Also I Have Method that will clear data from Preference.
  • Now, Our StorageUtil.dart is Ready. Lets move to our main.dart file.
  • First of all lets import StorageUtil.dart and material.dart in our main.dart file.
  • Then, make main void method. But Wait for one minute. We have to initialize our StorageUtil In our main void method.
  • Then make StatefulWidget class named *SharedPreference* that we define in runApp.
  • Now, when ever you want to set data into your Preference then just paste this code.
  • In Above line there is first value is our key that we will use to store and receive data. and second one is key value.
  • Now, how to get key value ? Its also very simple. Just Paste this code where ever you want value.
  • just define key_name. It will return value.
  • Here is my main.dart file Source.
  • Here is my StorageUtills.dart File Code

So Guys That’s It For How To Store And Get Data From Shared Preferences in Flutter. Hope you like our tutorial. Comment below Your thoughts and your queries. And Also Comment below your suggestion here.

Also Read How to Display Current DateTime in Flutter.

Leave a Comment

%d bloggers like this: