Hide chapters

Flutter Apprentice

Fourth Edition · Flutter 3.16.9 · Dart 3.2.6 · Android Studio 2023.1.1

Section II: Everything’s a Widget

Section 2: 5 chapters
Show chapters Hide chapters

Section IV: Networking, Persistence & State

Section 4: 6 chapters
Show chapters Hide chapters

10. Handling Shared Preferences
Written by Kevin D Moore

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Picture this: You’re browsing recipes and find one you like. You’re in a hurry and want to bookmark it to check it later. Can you build a Flutter app that does that? You sure can! Read on to find out how.

In this chapter, your goal is to learn how to use the shared_preferences plugin to save important pieces of information to your device.

You’ll start with a new project showing two tabs at the bottom of the screen for two views: Recipes and Groceries.

The first screen is where you’ll search for recipes you want to prepare. Once you find a recipe you like, just bookmark it, and the app will add the recipe to your Bookmarks page. It will also add all the ingredients you need to your shopping list. You’ll use a web API to search for recipes and store the ones you bookmark in a local database.

The completed app will look something like this:

This shows the Recipes tab with the results you get when searching for Pasta. It’s as easy as typing in the search text field and tapping the Search icon. The app stores your search term history in the combo box to the right of the text field.

When you tap a card, you’ll see something like this:

To save a recipe, just tap the Bookmark button. When you tap on the Bookmarks selector, you’ll see that the recipe has been saved:

If you don’t want the recipe anymore, swipe left or right, and you’ll see a delete button that allows you to remove it from the list of bookmarked recipes.

The Groceries tab shows the ingredients you need to make the recipes you’ve bookmarked.

You’ll build this app over the next few chapters. In this chapter, you’ll use shared_preferences to save simple data like the selected tab and also to cache the searched items in the Recipes tab.

By the end of the chapter, you’ll know:

  • What shared preferences are.
  • How to use the shared_preferences plugin to save and retrieve objects.

Note: Feel free to explore the entire app. There is a lot there to explore and learn that isn’t covered in the book. Copy any code you like for your projects.

Now that you know what your goal is, it’s time to jump in!

Getting Started

Open the starter project for this chapter in Android Studio. Open the pubspec.yaml file and click pub get, then run the app.

Notice the two tabs at the bottom — each will show a different screen when you tap it. Only the Recipes screen currently shows any UI. It looks like this:

App Libraries

The starter project includes quite a few libraries in pubspec.yaml:


Saving Data

There are three primary ways to save data to your device:

Saving Small Bits of Data

Why would you save small bits of data? Well, there are many reasons to do this. For example, you could save the user ID when the user has logged in — or if the user has logged in at all. You could also save the onboarding state or data the user has bookmarked to consult later.

The shared_preferences Plugin

shared_preferences is a Flutter plugin that allows you to save data in a key-value format so you can easily retrieve it later. Behind the scenes, it uses the aptly named SharedPreferences on Android and the similar UserDefaults on iOS.

shared_preferences: ^2.2.0

flutter pub get

How Does it Work?

The shared_preferences library uses the system’s API’s to store data into a file. These are small bits of information like integers, strings or Booleans. It has three main sets of function calls:

final sharedPrefs = await SharedPreferences.getInstance();
sharedPrefs.setString(CURRENT_USER_KEY, '1011442433');

Running Code in the Background

To understand the code you’ll be adding next, you need to know a bit about running code in the background.

Saving UI States

You’ll use shared_preferences to save a list of saved searches in this section. Later, you’ll also save the tab that the user has selected so the app always opens to that tab.

Adding Shared Preferences as a Provider

This app uses the Riverpod library to provide resources to other parts of the app. Chapter 13, “Managing State” covers Riverpod in more detail. For now, you want to create an instance of the SharedPreferences library on startup and provide it to other parts of the app. To do so, open up lib/providers.dart and import shared preferences library:

import 'package:shared_preferences/shared_preferences.dart';
final sharedPrefProvider = Provider<SharedPreferences>((ref) {
  throw UnimplementedError();
import 'package:shared_preferences/shared_preferences.dart';
import 'providers.dart';
// 1
final sharedPrefs = await SharedPreferences.getInstance();
// 2
runApp(ProviderScope(overrides: [
  // 3
], child: const MyApp()));

Adding an Entry

First, you’ll change the UI so that when the user presses the search icon, the app will add the search entry to the search list.

import '../../providers.dart';
static const String prefSearchKey = 'previousSearches';

Saving Previous Searches

Still in recipe_list.dart, replace // TODO Save Current Index with:

// 1
final prefs =;
// 2
prefs.setStringList(prefSearchKey, previousSearches);
// 1
final prefs =;
// 2
if (prefs.containsKey(prefSearchKey)) {
  // 3
  final searches = prefs.getStringList(prefSearchKey);
  // 4
  if (searches != null) {
    previousSearches = searches;
  } else {
    previousSearches = <String>[];

Showing the Previous Searches

To perform a search, you first need to clear any of your variables and save the new search value. Take a look at startSearch():

void startSearch(String value) {
  if (value.isEmpty) {
  // 2
  setState(() {
    // 3
    currentCount = 0;
    currentEndPosition = pageCount;
    currentStartPosition = 0;
    hasMore = true;
    value = value.trim();

    // 4
    if (!previousSearches.contains(value)) {
      // 5
      // 6

Testing the App

It’s time to test the app. You’ll see something like this:

Saving the Selected Tab

In this section, you’ll use shared_preferences to save the current UI tab that the user has navigated to.

import '../providers.dart';
static const String prefSelectedIndexKey = 'selectedIndex';
final prefs =;
prefs.setInt(prefSelectedIndexKey, _selectedIndex);
  // 1
final prefs =;
  // 2
if (prefs.containsKey(prefSelectedIndexKey)) {
    // 3
  setState(() {
    final index = prefs.getInt(prefSelectedIndexKey);
    if (index != null) {
      _selectedIndex = index;

Key Points

  • There are multiple ways to save data in an app: to files, in shared preferences and to a SQLite database.
  • Shared preferences are best used to store simple, key-value pairs of primitive types like strings, numbers and Booleans.
  • An example of when to use shared preferences is to save the tab a user is viewing, so the next time the user starts the app, they’re brought to the same tab.
  • The async/await keyword pair lets you run asynchronous code off the main UI thread and then wait for the response. An example is getting an instance of SharedPreferences.
  • The shared_preferences plugin shouldn’t be used to hold sensitive data. Instead, consider using the flutter_secure_storage plugin.

Where to Go From Here?

In this chapter, you learned how to persist simple data types in your app using the shared_preferences plugin.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now