Flutter – How to use shared_preferences store key-value pairs in persistent storage

Introduction

shared_preferences is a package in Flutter that provides a simple way to store key-value pairs in persistent storage. This can be useful for storing data that needs to persist across sessions, such as user preferences, app settings, or authentication tokens.

In this tutorial, we will explore how to use the shared_preferences package to store and retrieve data in your Flutter app.

Installation

To use the shared_preferences package in your Flutter app, you need to add it as a dependency in your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences:

Then, run flutter pub get to install the package.

Using shared_preferences

Once you have installed the shared_preferences package, you can start using it in your Flutter app. Here are the basic steps for using shared_preferences:

Import the shared_preferences package:

import 'package:shared_preferences/shared_preferences.dart';

Create an instance of SharedPreferences:

SharedPreferences prefs = await SharedPreferences.getInstance();

This creates a new instance of SharedPreferences that you can use to store and retrieve data.

Store data using the set methods:

prefs.setInt('counter', 42);
prefs.setDouble('pi', 3.14159);
prefs.setBool('is_logged_in', true);
prefs.setString('username', 'John Doe');

These methods set the value of a key-value pair in the shared preferences storage.

Retrieve data using the get methods:

int counter = prefs.getInt('counter');
double pi = prefs.getDouble('pi');
bool isLoggedIn = prefs.getBool('is_logged_in');
String username = prefs.getString('username');

These methods retrieve the value of a key-value pair from the shared preferences storage.

Delete data using the remove method:

prefs.remove('counter');

This method removes a key-value pair from the shared preferences storage.

Check if a key exists using the containsKey method:

bool hasUsername = prefs.containsKey('username');

This method returns true if the specified key exists in the shared preferences storage.

Retrieve a list of values: You can also use the getIntList, getDoubleList, and getStringList methods to retrieve a list of values stored under a key.

List<int> numbers = prefs.getIntList('numbers');
List<double> prices = prefs.getDoubleList('prices');
List<String> names = prefs.getStringList('names');

These methods return a list of values stored under the specified key.

If you need to store more complex data structures, you can use the jsonEncode and jsonDecode functions from the dart:convert package to convert them to and from JSON.

Map<String, dynamic> user = {'name': 'John Doe', 'age': 30};
String jsonUser = jsonEncode(user);
prefs.setString('user', jsonUser);

String jsonUser = prefs.getString('user');
Map<String, dynamic> user = jsonDecode(jsonUser);

These functions allow you to store and retrieve complex data structures in shared preferences.

Full Example

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textEditingController = TextEditingController();
  late SharedPreferences _prefs;
  String _savedText = '';

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

  // Initialize SharedPreferences
  void _initPrefs() async {
    _prefs = await SharedPreferences.getInstance();
    setState(() {
      _savedText = _prefs.getString('saved_text') ?? '';
    });
  }

  // Save text to SharedPreferences
  void _saveText(String text) {
    _prefs.setString('saved_text', text);
  }

  // Clear text from SharedPreferences
  void _clearText() {
    _prefs.remove('saved_text');
    setState(() {
      _savedText = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SharedPreferences Example'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _textEditingController,
              decoration: InputDecoration(
                hintText: 'Enter some text',
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  String text = _textEditingController.text;
                  _saveText(text);
                  setState(() {
                    _savedText = text;
                  });
                },
                child: Text('Save'),
              ),
              SizedBox(width: 16.0),
              ElevatedButton(
                onPressed: () {
                  _clearText();
                },
                child: Text('Clear'),
              ),
            ],
          ),
          SizedBox(height: 16.0),
          Text(
            'Saved text: $_savedText',
            style: TextStyle(fontSize: 18.0),
          ),
        ],
      ),
    );
  }
}

In this example, we create a TextField widget where the user can enter some text, and two ElevatedButton widgets for saving and clearing the text. We also display the saved text using a Text widget.

In the initState method, we initialize the SharedPreferences instance and retrieve the saved text from persistent storage using the getString method. If there is no saved text, we default to an empty string.

When the user taps the save button, we retrieve the text from the TextField, save it to persistent storage using the setString method, and update the UI to display the saved text.

When the user taps the clear button, we remove the saved text from persistent storage using the remove method, and update the UI to display an empty string.

Finally, we display the saved text using a Text widget.

With this example, you should have a better understanding of how to use shared_preferences in Flutter to store and retrieve data in persistent storage.

Conclusion

In this tutorial, we explored how to use the shared_preferences package in Flutter to store and retrieve data in persistent storage.

We saw how to create an instance of SharedPreferences, store and retrieve data using the set and get methods, delete data using the remove method, and check if a key exists using the containsKey method.

We also looked at how to retrieve a list of values stored under a key, and how to store and retrieve more complex data structures using JSON encoding and decoding.

With these tools, you can easily store and retrieve data in your Flutter app, making it more flexible and user-friendly.

Related posts:

  1. Getting Started with sqflite in Flutter: How to use sqflite in Flutter?
  2. Advanced sqflite Techniques in Flutter: Error handling
  3. Advanced sqflite Techniques in Flutter: Batch, Migrations, Transactions, Debugging