Flutter Shared Preference - Manage Local Storage Data in Flutter Apps

Managing Local Storage Data in Flutter Apps with Shared Preferences and a Common Utility Class


It provides a simple key-value storage solution that can be used to store and retrieve primitive data types, such as booleans, integers, doubles, strings, and lists of strings. 

This makes it a useful tool for managing user preferences, caching data, and persisting app state.


dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.0


Usage: 

Shared Preferences can be used to store and retrieve key-value data in your Flutter app. It is particularly useful for storing small amounts of data that need to persist between app sessions. 

Some examples of data that could be stored using Shared Preferences include user preferences, app settings, and cached data.


Code:

import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefUtils {

  // Saves a boolean value with the given key to SharedPreferences
  static Future<bool> saveBool(String key, bool value) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setBool(key, value);
  }

  // Saves an integer value with the given key to SharedPreferences
  static Future<bool> saveInt(String key, int value) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setInt(key, value);
  }

  // Saves a double value with the given key to SharedPreferences
  static Future<bool> saveDouble(String key, double value) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setDouble(key, value);
  }

  // Saves a string value with the given key to SharedPreferences
  static Future<bool> saveString(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setString(key, value);
  }

  // Saves a list of strings with the given key to SharedPreferences
  static Future<bool> saveStringList(String key, List<String> value) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.setStringList(key, value);
  }

  // Retrieves a boolean value with the given key from SharedPreferences
  static Future<bool?> getBool(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(key);
  }

  // Retrieves an integer value with the given key from SharedPreferences
  static Future<int?> getInt(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt(key);
  }

  // Retrieves a double value with the given key from SharedPreferences
  static Future<double?> getDouble(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getDouble(key);
  }

  // Retrieves a string value with the given key from SharedPreferences
  static Future<String?> getString(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  // Retrieves a list of strings with the given key from SharedPreferences
  static Future<List<String>?> getStringList(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getStringList(key);
  }


  // Removing data from SharedPreferences
  static Future<void> removeData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);
  }

// Clearing all data from SharedPreferences
  static Future<void> clearData() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
  }
}

..

Properties:

  • saveBool(String key, bool value): Saves a boolean value with the given key to SharedPreferences.
  • saveInt(String key, int value): Saves an integer value with the given key to SharedPreferences.
  • saveDouble(String key, double value): Saves a double value with the given key to SharedPreferences.
  • saveString(String key, String value): Saves a string value with the given key to SharedPreferences.
  • saveStringList(String key, List<String> value): Saves a list of strings with the given key to SharedPreferences.
  • getBool(String key): Retrieves a boolean value with the given key from SharedPreferences.
  • getInt(String key): Retrieves an integer value with the given key from SharedPreferences.
  • getDouble(String key): Retrieves a double value with the given key from SharedPreferences.
  • getString(String key): Retrieves a string value with the given key from SharedPreferences.
  • getStringList(String key): Retrieves a list of strings with the given key from SharedPreferences.
  • removeData(String key): Removes data with the given key from SharedPreferences.
  • clearData(): Clears all data from SharedPreferences.

..

Code sample:

To call the functions from the SharedPrefUtils class, you can simply import the file where the class is defined and use the class name to call the function, like this:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_route/util/shared_preferences.dart';
class UserList extends StatefulWidget { const UserList({super.key}); @override State<UserList> createState() => _UserListState(); } class _UserListState extends State<UserList> {

  Future<void> userDetails() async {
    // Save a boolean value to SharedPreferences
    await SharedPrefUtils.saveBool('is_logged_in', true);
    // Retrieve a boolean value from SharedPreferences
    final isLoggedIn = await SharedPrefUtils.getBool('is_logged_in');
    if (kDebugMode) {
      print("output : $isLoggedIn");
    }
  }

  @override
  void initState() {
    super.initState();

    userDetails(); // to store and get user details using common shared preference utils

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: const Text('Demo'),
      ),
    );
  }
}

..

Call the function you need : 

To use the functions in this SharedPrefUtils class, you can follow these steps:

For example, to save a boolean value to SharedPreferences, you can call the saveBool function:


bool valueToSave = true;
String key = "myBooleanKey";

SharedPrefUtils.saveBool(key, valueToSave);

..

To retrieve the saved value, you can call the corresponding function:


String key = "myBooleanKey";

bool? retrievedValue = await SharedPrefUtils.getBool(key);

if (retrievedValue != null) {
  // Do something with the retrieved value
} else {
  // The value was not found in SharedPreferences
}

..

To remove a value from SharedPreferences, you can call the removeData function:


String keyToRemove = "myBooleanKey";

await SharedPrefUtils.removeData(keyToRemove);

..

To clear all data from SharedPreferences, you can call the clearData function:


wait SharedPrefUtils.clearData();

..

Note that all functions in this class are asynchronous, so you need to use the await keyword when calling them.

Comments