Open In App

Shared Preferences in Flutter

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Shared Preferences are a way of storing small information inside the application space. Storing small amounts of data within an application is a common requirement for modern apps. Whether it's tracking user authentication, saving settings, or preserving user preferences, maintaining data between sessions is essential. Flutter provides a simple and efficient solution for this through Shared Preferences. Shared preferences are the key value that allows you to store and retrieve simple data types across sessions.

In this article, we are going to learn how to implement a custom class to store and access values stored in shared preferences. Let's understand the use of shared preferences with an example.

Example Case for Shared Preferences

Suppose you want to keep track of user authentication. You want to store the information about the user authentication status so that the user does not need to authenticate each time they open the app. In this case, we can store authentication information like status, access token, and refresh token in the shared preferences and use them whenever we need them across the application.

Steps to Implement Shared Preferences in Flutter

In this example, we are going to see how we can store different type of data in the shared preferences.

Step 1: Create a New Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter.

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add  shared_preferences as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
     flutter:
       sdk: flutter
     shared_preferences: ^2.5.3

Now, run the below command in the terminal.

flutter pub get

OR

Run the below command in the terminal.

flutter pub add shared_preferences


Step 3: Import dependencies

To use libraries, import all of them in the respective .dart file.

import 'package:shared_preferences/shared_preferences.dart';


Step 4: Saving Data

Let's save different types of data like int, double, String, Boolean, and list.

i). Saving Int Data in Shared Preferences

Dart
Future<void> addIntToPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('intValue', 18);
}


ii). Saving Double Data in Shared Preferences

Dart
Future<void> addDoubleToPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setDouble('doubleValue', 3.14159265359);
}


iii). Saving String Data in Shared Preferences

Dart
Future<void> addStringToPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('stringValue', 'Hello, World!');
}


iv). Saving Boolean Data in Shared Preferences

Dart
Future<void> addBoolToPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('boolValue', true);
}


v). Saving List Data in Shared Preferences

Dart
Future<void> addStringListToPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setStringList('stringListValue', ['Hello', 'World']);
}


Step 5: Reading Data

Reading data in share preferences is as easy as storing. we need key to pass to shared preferences to get the value of data stored.

i). Reading Int Data From Shared Preferences

Dart
Future<int> readIntFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int intvalue = prefs.getInt('intKey') ?? 0;
    return intvalue;
}

ii). Reading Double Data From Shared Preferences

Dart
Future<double> readDoubleFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    double doubleValue = prefs.getDouble('doubleValue') ?? 0.0;
    return doubleValue;    
}

iii). Reading String Data in Shared Preferences

Dart
Future<String> readStringFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String stringValue = prefs.getString('stringValue') ?? '';
    return stringValue;
}

iv). Reading Boolean Data From Shared Preferences

Dart
Future<bool> readBooleanFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool boolValue = prefs.getBool('isDataSaved') ?? false;
    return boolValue;
}

v). Reading List From Shared Preferences

Dart
Future<bool> readListFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> listData = prefs.getStringList('stringListValue') ?? [];
    return listData.isNotEmpty;
}


Note : As you can notice we have used null-aware operator. this will ensure that when the value from shared preferences is empty, the value on the right hand side of this operator gets assigned to variable.

Syntax:

variable = expression1 ?? expression2;
  • variable: Is the variable that will be assigned the value.
  • expression1: Is the first expression, which is checked for null.
  • expression2: Is the second expression, which is the default value to be used if expression1 is null.


Creating a Custom Shared Preferences Class

Now we have a basic idea of how to implement shared preferences in Flutter. Let's see how we can make a custom class of shared preferences.

Step 1: Creating a class

Create a class and name it as per your need. In this case, SharedPreferencesManager.

Dart
class SharedPreferencesManager {}


Step 2: Declaring Keys for Shared Preferences

In this step, all you need to do is brainstorm your application idea and get the requirements for which data or values need to store in the shared preferences. accordingly you need to declare the keys, for example. In authentications scenario we might need to store user-id, access token, etc. so the keys would be the "user_id", "access_token" .

Dart
final String intKey = "intValue";
final String doubleKey = "doubleValue";
final String stringKey = "stringValue";
final String boolKey = "boolValue";
final String listKey = "stringListValue";


Step 3: Declare All the Required Methods

Declaring the methods that will help store the shared preferences and retrieve them when the method is called.

Dart
/// Methods for writing data from shared preferences
Future<void> addIntToPref(intData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt(intKey, intData);
}

Future<void> addDoubleToPref(doubleData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setDouble(doubleKey, doubleData);
}

Future<void> addStringToPref(stringData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(stringKey, stringData);
}

Future<void> addBoolToPref(boolData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(boolKey, boolData);
}

Future<void> addStringListToPref(listData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(listKey, listData);
}

/// Methods for reading data from shared preferences
Future<int> readIntFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(intKey) ?? 0;
}

Future<double> readDoubleFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getDouble(doubleKey) ?? 0.0;
}

Future<String> readStringFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(stringKey) ?? '';
}

Future<bool> readBoolFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(boolKey) ?? false;
}

Future<List<String>> readListFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getStringList(listKey) ?? [];
}


As we can see, we have declared methods to store shared preferences as well as read shared preferences. Using the object of this class, we can easily call the methods to read and write data.


Step 4: Storing Data in Shared Preferences using a Custom class Object

The next thing we need to do is create an object of the "SharedPreferencesManager" class and use it to perform operations.

Dart
// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();

// Call the addIntToPref method and pass the integer value
prefManager.addIntToPref(10);

// Call the addDoubleToPref method and pass the double value
prefManager.addDoubleToPref(10.5);

// Call the addStringToPref method and pass the string value
prefManager.addStringToPref('Hello World');

// Call the addBoolToPref method and pass the boolean value
prefManager.addBoolToPref(true);

// Call the addStringListToPref method and pass the list of strings
prefManager.addStringListToPref(['One', 'Two', 'Three']);


Step 5: Retrieving Data from Shared Preferences Using a Custom Class Object

Similarly, we will now call the methods to read the data from shared preferences. we are assigning these values or data to variables hence we can use them later. for this we are making one method and inside it reading all the data.

Dart
bool isDataRead = false;
int intValue = 0;
double doubleValue = 0.0;
String stringValue = '';
bool boolValue = false;
List<String> stringListValue = [];

// Create an object of SharedPreferencesManager class
SharedPreferencesManager prefManager = SharedPreferencesManager();

// Method to read data from shared preferences
void readData() async {
    intValue = await prefManager.readIntFromPref();
    doubleValue = await prefManager.readDoubleFromPref();
    stringValue = await prefManager.readStringFromPref();
    boolValue = await prefManager.readBoolFromPref();
    stringListValue = await prefManager.readListFromPref();

}


As we can see, the readData() method is used to read data by calling methods declared in the custom class and assigning values to declared variables.


Here is the whole functional code:

main.dart
import 'package:flutter/material.dart';
import 'package:flutter_sharedpref/my_home_page.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Shared Preferences',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}
my_home_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_geeks/read_data_screen.dart';
import 'package:flutter_geeks/shared_preferences_manger.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isDataSaved = false;

  // Create an object of SharedPreferencesManager class
  SharedPreferencesManager prefManager = SharedPreferencesManager();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            isDataSaved
                ? const Text('Data Saved!')
                : const Text('Data Not Saved!'),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
              ),
              onPressed: () {
                // Call the addIntToPref method and pass the integer value
                prefManager.addIntToPref(10);
                // Call the addDoubleToPref method and pass the double value
                prefManager.addDoubleToPref(10.5);
                // Call the addStringToPref method and pass the string value
                prefManager.addStringToPref('Hello World');
                // Call the addBoolToPref method and pass the boolean value
                prefManager.addBoolToPref(true);
                // Call the addStringListToPref method and pass the list of strings
                prefManager.addStringListToPref(['One', 'Two', 'Three']);
                setState(() {
                  isDataSaved = true;
                });
              },
              child: const Text('Save Data'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
              ),
              onPressed: () async {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => ReadDataScreen()),
                );
              },
              child: const Text('Go to Next Screen'),
            ),
          ],
        ),
      ),
    );
  }
}
read_data_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_geeks/shared_preferences_manger.dart'
    show SharedPreferencesManager;

import 'package:shared_preferences/shared_preferences.dart';

class ReadDataScreen extends StatefulWidget {
  const ReadDataScreen({super.key});

  @override
  State<ReadDataScreen> createState() => _ReadDataScreenState();
}

class _ReadDataScreenState extends State<ReadDataScreen> {
  bool isDataRead = false;
  int intValue = 0;
  double doubleValue = 0.0;
  String stringValue = '';
  bool boolValue = false;
  List<String> stringListValue = [];

  // Create an object of SharedPreferencesManager class
  SharedPreferencesManager prefManager = SharedPreferencesManager();

  // Method to read data from shared preferences
  void readData() async {
    intValue = await prefManager.readIntFromPref();
    doubleValue = await prefManager.readDoubleFromPref();
    stringValue = await prefManager.readStringFromPref();
    boolValue = await prefManager.readBoolFromPref();
    stringListValue = await prefManager.readListFromPref();
    setState(() {
      isDataRead = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Read Data'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white,
              ),
              onPressed: () {
                readData();
              },
              child: const Text('Read Data'),
            ),
            const SizedBox(height: 20),
            isDataRead
                ? Column(
                  children: [
                    Text('Int Value: $intValue'),
                    Text('Double Value: $doubleValue'),
                    Text('String Value: $stringValue'),
                    Text('Bool Value: $boolValue'),
                    Text('String List Value: $stringListValue'),
                  ],
                )
                : const Text('Data Not Read!'),
          ],
        ),
      ),
    );
  }
}
shared_preferences_manger.dart
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesManager {
  final String intKey = "intValue";
  final String doubleKey = "doubleValue";
  final String stringKey = "stringValue";
  final String boolKey = "boolValue";
  final String listKey = "stringListValue";

  /// Methods for writing data from shared preferences
  Future<void> addIntToPref(intData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt(intKey, intData);
  }

  Future<void> addDoubleToPref(doubleData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setDouble(doubleKey, doubleData);
  }

  Future<void> addStringToPref(stringData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(stringKey, stringData);
  }

  Future<void> addBoolToPref(boolData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(boolKey, boolData);
  }

  Future<void> addStringListToPref(listData) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(listKey, listData);
  }

  /// Methods for reading data from shared preferences
  Future<int> readIntFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(intKey) ?? 0;
  }

  Future<double> readDoubleFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getDouble(doubleKey) ?? 0.0;
  }

  Future<String> readStringFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(stringKey) ?? '';
  }

  Future<bool> readBoolFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(boolKey) ?? false;
  }

  Future<List<String>> readListFromPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getStringList(listKey) ?? [];
  }
}

Output:

Conclusion

In this article we have learned how to create custom shared preferences class in flutter by implementing simple app which will store and retrieve some basic data. It used package called "shared_preferences". we can use this method to build scalable applications which will be easy to manage and maintain.


Next Article

Similar Reads