Your Second Flutter App

Nov 30 2021 · Dart 2.13, Flutter 2.2.3, Visual Studio Code

Part 4: Filter Results

28. Use Shared Preferences

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 27. Challenge: Add a Filter Next episode: 29. Filter Courses

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 28. Use Shared Preferences

Another key part of providing a solid user experience in your app is saving data that your user has entered so that it survives between app restarts.

In some cases, you can just save the data locally in the app. In others, you many want to also send the data over the network to a backend server, so that it gets associated with an account for your user.

When saving data locally, you have a number of options. One is to saving data to files, by opening a file, writing data to the file, then closing the file.

For more complicated data, especially data that has some relational structure to it, you would want to save the data in a database. One example would be saving to a SQLite database. You’ll see how to do that in a later course in our Flutter Learning Path.

Another way to save data is useful when the data is relatively simple and has a key-value type structure, that is, you want to save pairs of data items in which one item in the pair acts as a key, and the other acts as a value. A typical use case for key value pairs is the settings screen of an app, where the particular setting acts like a key, and the value the user chooses for the setting is a value.

The Flutter package shared_preferences lets you store key value data and persist it for your app. Behind the scenes on iOS, this package uses UserDefaults, and on Android, the package uses a features that also goes by the name SharedPreferences.

To get started, open your project in progress or download the sample project for this episode. Now run your app. Open the filter page and select a filter. Now you’ll see that when you return back to the course page, you will see all the courses which is a definite bug. Don’t worry, we’ll fix that soon. But if you return back to the filter page, your selection is gone.

We need to persist this and shared preferences is a great way to do that. First, look up shared preferences documentation for flutter. You can find it over here:

https://pub.dev/packages/shared_preferences

Click on the Installing tab. There you will get your installation instructions. Copy the installation command. Now switch back to Visual Studio Code and open the terminal tab. Copy the shared_preferences installation command into the terminal.

flutter pub add shared_preferences

This will download the library and all the dependencies. Keep in mind, you can also manually update pubspec.yaml. Now to incorporate Shared Preferences. Open up filter_page.dart in the filter subfolder. Inside of _FilterPageState, add a helper method _loadValue.

void _loadValue() {

}

This method will be used to load the currently saved FilterValue when FilterPage is first opened. Now call getInstance on the SharedPreferences class to set a prefs variable in the method. The call to getInstance is asynchronous, so we need to use the async/await keywords.

  _loadValue() async {
    final prefs = await SharedPreferences.getInstance();
  }

Make sure to import the SharedPreferences library.

import 'package:shared_preferences/shared_preferences.dart';

Once we have prefs, we then want to call setState and set the filterValue for the FilterPage. We will set it, using the current value for the filter that is stored in shared preferences.

void _loadValue() async {
  final prefs = await SharedPreferences.getInstance();
  setState(() {
    _filterValue = prefs.getInt(Constants.filterKey) ?? 0;
  });
}

We call getInt on shared preferences to get the value. Now we pass in a constant value for the key that identifies the key in SharedPreferences that we are accessing. Of course, if we find a null value, we simply set the value to zero.

Add initState and a call to _loadValue.

class _FilterPageState extends State<FilterPage> {
  int _filterValue = Constants.allFilter;

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

    _loadValue();
  }

Update _handleRadioValueChanged method to save the filter selected by a user.

  void _handleRadioValueChange(int? value) async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _filterValue = value ?? 0;
      prefs.setInt(Constants.filterKey, _filterValue);
    });
  }

Here again we get the SharedPreferences instance, and call setState to set the filter value. We also save the selected value into shared preferences using setInt.

Okay, let’s try this out and see how it works. Build and run or hot reload your app. Head over to the filter page. Select an option. Go back, and then back to filter page. You’ll see that your filter option is selected. But of course, going back to the course listing, you’ll see all the courses without the filter applied. We will do that in the next episode.