How to Use Shared Preferences in Flutter (Step-by-Step Guide)

shared preferences in flutter full guide
Shared-preferences in flutter Step by Step tutorial

When building mobile apps, storing small bits of data—like login status, user settings, or preferences—is a common requirement. That’s where SharedPreferences in Flutter comes to the rescue! It offers a simple way to save key-value pairs locally, so your app can remember things even after it’s closed. In this step-by-step guide, we’ll walk you through exactly how to set up and use SharedPreferences in Flutter, with real code examples to help you implement it quickly and effectively. Whether you’re saving a user’s theme choice or a simple login flag, this guide will help you get it done in minutes!

In this blog, we will explore:

  • What is Shared Preferences?
  • How to integrate it into a Flutter project
  • Writing, reading, and deleting data
  • Understanding how Shared Preferences works internally
  • Limitations and best practices

What is SharedPreferences in Flutter?

SharedPreferences is a way to save small bits of data on the user’s phone. It helps your app remember things like:

  • If the user is logged in
  • The theme they chose (dark or light)
  • Their name or email
  • App settings or preferences

This data stays saved even when the app is closed or the phone is restarted.

How to use shared preferences in Flutter?

To use Shared Preferences, we have to use package so add the following dependency in pubspec.yaml:

Step 1: Add the package

Then run this command in your terminal:

Step 2: Import SharedPreferences

Now, import the package into your Dart file:

import 'package:shared_preferences/shared_preferences.dart';

Step 3: Save Data

To save data, use the set methods of SharedPreferences:

Future<void> saveData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();

await prefs.setString('username', 'JohnDoe');
await prefs.setInt('age', 25);
await prefs.setDouble('height', 5.9);
await prefs.setBool('isDarkMode', true);
await prefs.setStringList('hobbies', ['Reading', 'Gaming', 'Coding']);
}

Step 4: Read Dat

To fetch stored data, use the corresponding get methods:

Future<void> readData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();

String? username = prefs.getString('username');
int? age = prefs.getInt('age');
double? height = prefs.getDouble('height');
bool? isDarkMode = prefs.getBool('isDarkMode');
List<String>? hobbies = prefs.getStringList('hobbies');

print('Username: $username');
print('Age: $age');
print('Height: $height');
print('Dark Mode: $isDarkMode');
print('Hobbies: $hobbies');
}

Step 5: Removing Data

To delete a specific key:

Future<void> removeData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('username');
}

To clear all stored preferences:

Future<void> clearData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.clear();
}

How Shared Preferences Works Internally

Platform-Specific Storage

Flutter is a cross-platform framework, but SharedPreferences uses native storage under the hood:

  • 📱 Android → Uses SharedPreferences API from Android SDK. It saves data in an XML file in the app’s internal storage.
  • 🍎 iOS → Uses NSUserDefaults, Apple’s built-in storage for user preferences.
  • 🖥️ Web → Uses window.localStorage (browser’s local storage).

Flutter’s shared_preferences package is a wrapper that gives you one simple Dart API, while doing the platform-specific stuff behind the scenes.

Key-Value Storage

All data is stored as simple key-value pairs, such as:

dart"username" : "John"
"isLoggedIn" : true

It supports only basic data types:

  • String
  • int
  • double
  • bool
  • List<String>

Each key must be unique, like a label for your data.

Saves to Disk Automatically

When you call something like:

prefs.setString('name', 'Alex');

It,

  • Calls the Dart-side method
  • Sends a message via platform channels to the native platform
  • The native code (Java/Kotlin on Android, Swift/Obj-C on iOS) saves it to persistent storage

The data is stored on the device’s disk and stays available even after app restarts.

No Encryption (by Default)

SharedPreferences is meant for simple preferences, not secure data like passwords or tokens. If you need secure storage, consider using:

  • flutter_secure_storage
  • EncryptedSharedPreferences on Android

Summary

PlatformStorage Used
AndroidSharedPreferences (XML files)
iOSNSUserDefaults
Webwindow.localStorage

Limitations

  • Not for large data: Shared Preferences is not optimized for large data sets.
  • No encryption: Data is stored in plain text; do not use it for sensitive information.
  • Limited to primitive types: Does not support complex objects like maps or custom classes.

Best Practices

  • Use Shared Preferences only for simple key-value data.
  • Avoid storing large data structures; use a local database like SQLite or Hive for that.
  • If you need encryption, use flutter_secure_storage instead.
  • Always handle null values when retrieving data to prevent crashes.

Conclusion

Shared Preferences in Flutter is an easy-to-use solution for storing user preferences and lightweight data. By understanding its workings, limitations, and best practices, you can use it effectively in your apps. Happy coding!!

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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