How to Save Index of PageView in SharedPreferences- Flutter

Table Of Contents

Introduction

Creating the project

Add SharedPreferences as a Dependency

Complete Code

Conclusion

Introduction

Sometimes when building an app, the app might require that we track the user's activity by resuming the last page they assessed instead of starting from the beginning when using a PageView. This becomes important in situations where a large collection of images, such as scrolling through 1000 pictures, is displayed using a PageView. In such cases, it is better to be able to leave the app and return to the last viewed picture upon reopening the app. This will save us from the stress of starting from the first picture each time. This is exactly what we will achieve in this tutorial.

In this tutorial, we will learn how to create a PageView and how to save the index of the PageView in SharedPreferences.

Let's get started!

Creating the project

Navigate to any directory you like and run the below code to create a new flutter project.

flutter create pageview_with_sharedpreferences

Open the project in your preferred Editor.

Add SharedPreferences as a Dependency

Let's start by explaining what Sharepreferences is.

SharedPreferences is a Flutter plugin that enables persistent storage of small, key-value pairs on the device. It stores user preferences, settings, and other data that need persistence across different app sessions.

SharedPreferences is used to store user login credentials, app theme preferences, language settings, and other app-specific configurations that require preservation between app launches.

In case you are confused about the above explanation of SharedPreferences, here is what you need to know;

SharedPreferecences allow you to save data in the form of key-value pairs in your device. With SharedPreferences, you can save and retrieve data on your device whenever you need it.

With the above explanation, we now see why we need it in our application.

After a brief explanation of SharedPreferences, It is time to use it in our project. Go to your terminal and add it as a dependency by running the code below.

flutter pub add shared_preferences

Your pubspec.yaml file should have SharedPreferences added as a package just like the image below.

Complete Code

Let's change the code in our main file after we have installed the dependency. For simplicity, we will use a simple PageView design and save the index of the pageview in SharedPreferences. The PageView children will consist of four containers with different colors. Each container will have a text widget as its child.

Copy and paste the code below to replace what we have in the main file.

NB: Please make sure to read the commented lines in the code for better understanding.

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

void main() => runApp(const MyPageView());

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

  @override
  State<MyPageView> createState() => _MyPageViewState();
}

class _MyPageViewState extends State<MyPageView> {
  late PageController pageViewController;

  @override
  void initState() {
    super.initState();
//this is called in the initState so as to get
//the latest index
    _loadIndex();
  }

  _loadIndex() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
//this retrieves the index of pageview from
//SharedPreferences
    int index = prefs.getInt('index') ?? 0;
    setState(() {
      pageViewController = PageController(initialPage: index);
    });
  }

  _saveIndex(int index) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
//this saves the index of pageview
    await prefs.setInt('index', index);
  }

  @override
  void dispose() {
    pageViewController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            Expanded(
              child: PageView(
                controller: pageViewController,
                children: [
                  Container(
                    height: 50,
                    width: 50,
                    color: Colors.red,
                    child: const Center(
                      child: Text(
                        "this is red",
                        style: TextStyle(color: Colors.white, fontSize: 24),
                      ),
                    ),
                  ),
                  Container(
                    height: 50,
                    width: 50,
                    color: Colors.green,
                    child: const Center(
                      child: Text(
                        "this is green",
                        style: TextStyle(color: Colors.white, fontSize: 24),
                      ),
                    ),
                  ),
                  Container(
                    height: 50,
                    width: 50,
                    color: Colors.blue,
                    child: const Center(
                      child: Text(
                        "this is blue",
                        style: TextStyle(color: Colors.white, fontSize: 24),
                      ),
                    ),
                  ),
                  Container(
                    height: 50,
                    width: 50,
                    color: Colors.yellow,
                    child: const Center(
                      child: Text(
                        "this is yellow",
                        style: TextStyle(color: Colors.white, fontSize: 24),
                      ),
                    ),
                  ),
                ],
                onPageChanged: (index) {
                  setState(() {
        //This saves the index of pageview to 
        //sharedpreferences when we use 
        //"next" or "prev" buttons
                    _saveIndex(index);
                  });
                },
              ),
            ),
            Container(
              height: 50,
              child: Padding(
                padding: const EdgeInsets.all(15.0),
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        pageViewController.previousPage(
                          duration: const Duration(milliseconds: 500),
                          curve: Curves.easeIn,
                        );
                      },
                      child: Container(
                        child: const Text(
                          "prev",
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ),
                    const Spacer(),
                    InkWell(
                      onTap: () {
                        pageViewController.nextPage(
                          curve: Curves.easeIn,
                          duration: const Duration(milliseconds: 500),
                        );
                      },
                      child: Container(
                        child: const Text(
                          "Next",
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Let's explain what we have in the above code.

We created two functions which are;

  • _saveIndex

  • _loadIndex

_saveIndex saves the updated index in SharedPreferences whenever a user changes the page by tapping the "prev" or "Next" buttons. We used the _saveIndex in the onPageChanged function of the PageView.

_loadIndex retrieves the last saved index from SharedPreferences, and it's called on the initState. These allow us to get the latest page index before rendering the app.

Your emulator should look like what is below when you run the code.

You can move from one page to another by tapping the "Next" or "Prev" buttons.

Whenever you leave the app, the index of the PageView will be stored to SharedPreference using the _saveIndex method and will be retrieved when you reopen the app using the _loadIndex method in initState. You can check this by performing a hot restart.

This is how we can save the index of PageView using SharedPreferences so that we can reopen the app from where we last use it.

Conclusion

In this tutorial, we learnt how to use SharedPreference to save the index of PageView in Flutter.

If you are new to SharedPreferences, please visit the link here to learn more about the package.

Thank you for sticking through.

Happy Coding!