Skip to content

DKEMMET

The IT Journal

Menu
  • Home
  • About
  • Posts
  • At A Glance
Menu

Flutter Apprentice (v3.0) – Handling Shared Preferences

Posted on October 20, 2022October 20, 2022 by dj

Getting started

Fetch deps and get the app ready to debug.

App libraries

Saving data

So what this chapter basically tries to outline is that what we’re doing with the plugins consumed in this chapter:

  1. cached_network_image
  2. flutter_slidable
  3. platform
  4. flutter_svg

is coming up with quick ways to store a little bit of information on the device. this isn’t mean to replace or help things you need a database for.

Why save small bits of data?

basically to facilitate core pieces of the application state like is the user signed in, what feature flags do they have set etc etc. you would so this in leu of storing this kind of information in something like an “app state” table.

you should not use shared_preferences to store sensitive information like passwords and API Tokens.

The shared_preferences plugin

It’s consumes SharedPreferences on Android and UserDefaults on iOS

Saving UI states

Adding an entry to the search list

Running code in the background

  • Asynchronous – Async marks a method as async
  • Await – used inside a method to have a command wait

Saving previous searches

  void savePreviousSearches() async {
    // 1 - we're instantiating an instance of android's
    //     shared_preferences, which itself is async so we're using
    //     the await keyword when we instantiate.
    final prefs = await SharedPreferences.getInstance();
    // 2
    prefs.setStringList(prefSearchKey, previousSearches);
  }

So what’s cool is it looks like SharedPreferences presents what is basically a join method. Then we created the equivalent of GET method for our UI to consume, it looks like:

  void getPreviousSearches() async {
    // 1 - Instantiate sharedPreferences
    final prefs = await SharedPreferences.getInstance();
    // 2 - check for a list of previous search keys.
    if (prefs.containsKey(prefSearchKey)){
      // 3 - declare a final list of searches created from our
      //     list of existing searchs.
      final searches = prefs.getStringList(prefSearchKey);
      // 4 - if that list isn't empty
      if (searches != null) {

        // update our previousSearches list to be the same as
        // the list of search keys gathered from our shared preferences
        // plugin. 
        previousSearches = searches;
      } else {
        
        // otherwise, create the variable with an empty list designated to hold
        // strings. 
        previousSearches = <String>[];
      }
    }
  }

Adding the search functionality

So the METHOD BY WHICH WE DO THIS is to create a function that directly updates the state of the widget, in this case RecipeList.

  void startSearch(String value) {
    // 1
    setState((){
      // 2 - all the properties of the widget's state. we're basically
      //    resettings.
      currentSearchList.clear();
      currentCount = 0;
      currentEndPosition = pageCount;
      currentStartPosition = 0;
      hasMore = true;
      value = value.trim();

      // 3 - the logic that is responsible for assing a search key that
      //     is not already in the list of previous searches.
      if (!previousSearches.contains(value)){
        // 4
        previousSearches.add(value);
        // 5
        savePreviousSearches();
      }

    });
  }

Adding a search button

Not going to lie, I definitely copy and pasted a huge chunk of this section’s code into my browser but I get what it’s doing.

Test the app

Nothing to note.

Saving the selected tab

Nothing of Note.

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 let 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 should not be used to hold sensitive data. Instead, consider using the flutter_secure_storage plugin.
Post Views: 185

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • ACG Labs
  • Automation
    • Ansible
  • AWS
    • Cloud Formation
    • ECS
    • S3
  • Books
    • Dart Apprentice
    • Flutter Apprentice
  • Certification Prep
    • LPIC-1,101
  • Docker
  • Platforms
    • Linux
    • Windows
  • Programming
    • Dart / Flutter
    • Python
  • Projects
    • Build "MyOS" (Debian, i3)
    • Fullstack App Dev (Flutter, Python)