Flutter Shared Preferences

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 21, 2023

Flutter Shared Preferences: A Quick Guide

When working on mobile app development with Flutter, persisting user data is a crucial aspect. Flutter provides us with a simple and easy-to-use package to manage and store data called shared_preferences.

What is shared_preferences?

shared_preferences is a Flutter plugin that provides a way to store simple data in key-value pairs on the user's device. The plugin abstracts away the native implementation details, making it easy to use from Dart code. With shared_preferences, you can store and retrieve data that can be used to tailor the user's app experience, such as their preferences, settings, or user information.

How to use shared_preferences

In order to use shared_preferences, you first need to add the package to your Flutter project. To do this, add the following line to your pubspec.yaml file:


dependencies:
  shared_preferences: ^2.0.5


After adding the package, you can start using it in your app. Here's a quick example:


import 'package:shared_preferences/shared_preferences.dart';

saveUserDetails(String name, String email) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('username', name);
  prefs.setString('email', email);
}

getUserDetails() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String username = prefs.getString('username');
  String email = prefs.getString('email');

  return {'name': username, 'email': email};
}


In this example, we've created two functions to save and retrieve user details. The saveUserDetails() function takes in two parameters - name and email - and saves them to shared preferences using the instance of SharedPreferences. Similarly, the getUserDetails() function fetches the user's details from shared preferences and returns them as a map.

Conclusion

Using shared_preferences, you can easily store and retrieve simple data in your Flutter app, making it easier to tailor the user experience and remember user preferences. With just a few lines of code, you can persist user data and enhance the user's experience.