Flutter shared preferences example

Shared preferences is one of the way of storing and retrieving data in android. The procedures like one time login is achieved through shared preferences in mobile applications. We already discussed the concept in one of our previous tutorials for native android. Here we will try to implement the same in flutter applications.

Content

  • Import library for shared preferences
  • Boolean shared preferences
  • String shared preferences
  • Integer shared preferences

Importing Library

Flutter is not having any default class for implementing shared preferences. So if we need to achieve this feature we definitely need a library. For importing the shared preference library open your pubsec,yaml file and add the following dependency. And click on get packages.

shared_preferences:

After getting the dependencies you need to have the following import statement in all the dart files which you are planning to use the shared preferences.

import 'package:shared_preferences/shared_preferences.dart';

Now we have the library and we can start implementing code for storing and retreiving the shared preferences. Following is the code for storing and retrieving based on types. You can use the one which is based on your requirement.

Boolean shared preferences

Storing boolean shared preferences

SetSharedVariables() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setBool('your_key', true);
}

Retreiving boolean shared preferences

GetSharedVariables() async {
 bool out = pref.getBool('Your key');
}

String shared preferences

Storing string shared preferences

SetSharedVariables() async {
  SharedPreferences pref = await SharedPreferences.getInstance();
  pref.String('your_key', 'your string');
}

Retreiving string shared preferences

GetSharedVariables() async {
String out = pref.getString('Your key');
}

Integer shared preferences

Storing int shared preferences

SetSharedVariables() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setInt('your_key', 1);
}

Retreiving int shared preferences

GetSharedVariables() async {
int out = pref.getInt('Your key');
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *