Mohit Khare
Mohit Khare Product Engineer @ gojek | Blogs about tech, productivity and life.

Storing with Shared Preferences in Flutter

Storing with Shared Preferences in Flutter

We usually want to persist some of the data in our apps. Eg. Storing user data, some flags, local user settings,etc. There are multiple ways to achieve this. You must be aware of multiple options for that -

  1. Storing in some DB integrated with backend.
  2. Storing it using SQLite. (Local database)
  3. Storing using Shared Preferences. (Key-value Store)
  4. Storing it using Firebase. (Remote DB)
  5. Using File storage

You guessed it right from the title. We’ll be discussing Shared Preferences here.

What is Shared Preferences?

Essentially shared preferences are a key-value store at the core. It is generally used to store and retrieve small amounts of primitive data. This is maintained in the local device using a file that maintains a map.

Flutter utilizes following for implementing shared preferences -

  • NSUserDefaultson iOS
  • SharedPreferences on Android

Some of the use cases when we can use shared preferences are -

  • When you want to store user settings.
  • Implementing auto-login
  • Saving some flags which hide and show content based on conditions.

Enough talking? Let’s Code 🤘

We’ll be using the shared_preferences package in flutter. Let’s add this to our pubspec.yaml.
Read about how to use external packages in flutter here.

1
2
3
4
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^0.5.6+3"

Run flutter pub get to get the package. You can add the latest version from here.

Here, i’ll be using autologin as an example to demonstrate use of shared preferences.

We will maintain a isLoggedIn boolean variable, whose value

  • if true signifies that user is authenticated and can be logged in without reentering password.
  • if false signifies user authentication is required.

Save the value

Let’s first save a boolean variable in our key store.

1
2
3
4
5
6
saveBoolValue(String key, bool value) async {
	// get shared preference instance.
	SharedPreferences prefs = await SharedPreferences.getInstance();
	// Set the key ('isLoggenIn') with a value (true/false) here.
	prefs.setBool(key, value);
}

Yes, that’s all you need to save a bool value. Already with love in Flutter right? You can save strings, integer, double values too in similar fashion -

  • setString(key, value) - for storing strings
  • setInt(key, value) - for storing integers
  • setDouble(key, value) - for storing double

Cool, now that we have stored a value. Let’s verify it by getting the value back?

Get the value

1
2
3
4
5
6
7
getBoolValue(String key) async {
	// get shared preference instance.
	SharedPreferences prefs = await SharedPreferences.getInstance();
	// Get the value with given key.
	bool isLoggedIn = prefs.getBool(key); // in our case key => 'isLoggedIn'
	return isLoggedIn;
}

That works 😎

Note: We get a null value if key doesn’t exists.

Wait, don’t say Mohit I also want to delete some values. Okay, sure let’s do that too 😄

Remove Key-Value pair

1
2
3
4
5
6
removeData(String key) async {
	// get shared preference instance.
	SharedPreferences prefs = await SharedPreferences.getInstance();
	// Remove the key.
	prefs.remove(key);
}

Check if key exists

You can also check if shared preferences contains a key or not?

1
2
3
4
5
6
checkIfKeyExists(String key) async {
	// get shared preference instance.
	SharedPreferences prefs = await SharedPreferences.getInstance();
	// Check if the key exists.
	return prefs.containsKey(key);
}

Coming back to autoLogin. See the implementation below -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
login() {
	// Perform username, password check before this.
	saveBoolValue('isLoggedIn',true);
	// Authenticated! Navigate to home screen.
}

logout() {
	saveBoolValue('isLoggedIn',false);
	// Unauthorized now! Navigate to login screen.
}

autoLogin() {
	bool isLoggenIn = getBoolValue("isLoggedIn")
	if(isLoggedIn) {
		// Authenticated! Navigate to home screen.
	} else {
		// Unauthorized! Navigate to login screen.
	}
}

Place your autoLogin in init() on your home screen class.

Awesome, we did it! 😎

Now, you have good knowledge of shared preferences. Try to implement this in your apps. 🚀 Do drop a 👍 and share it with your friends.

Interested in more technology-oriented stuff? Follow me on twitter. I hope you learned something interesting and new.

I share updates/knowledge almost daily on Twitter. Reach out to me at mohitkhare.me

FightCorona

comments powered by Disqus