Using shared_preferences to save data in Android, iOS, and the web

The shared_preferences plugin allows simple data (key-value pairs) to be asynchronously persisted locally and is currently available for Android, iOS, and Flutter for Web.

This is possible because shared_preferences wraps different technologies based on the system on which it's run. In iOS, it leverages NSUserDefaults; in Android, it leverages SharedPreferences, and in the browser, it leverages the window.localStorage object. Basically, you have a universal way to save data and don't have to worry about duplicating any code for the different devices on which your app will be running.

shared_preferences should not be used for critical data as data stored there is not encrypted, and writes are not always guaranteed. For sensitive or critical data, other technologies that we've used in previous chapters, such as sembast and the Firestore database, are already compatible with Flutter for Web.

At this time, there are already several libraries that also support Flutter for Web, but many of them don't. Things are changing very fast, and I wouldn't be surprised if, by the time you read this, most of the libraries that are not totally device-specific become available for the web (and for desktop).

For an updated list of the libraries that currently support Flutter for Web, have a look at the following page: https://pub.dev/flutter/packages?platform=web.

Now, let's add the code to persist data into our app.

We'll use the existing bookshelper.dart file to add the methods to read and write to shared_preferences. We'll need three methods: one to add items to the favorites, one to remove them, and one to get the favorites list. We'll begin by adding favorites to shared_preferences, as follows:

  1. In the BooksHelper class, add a new asynchronous method called addToFavorites(). This will take a Book object and return a Future. In the method, call an instance of SharedPreferences called preferences.
  2. Next, we will check if the book already exists in the local storage: if it doesn't, call the setString() method of the preferences to add it to the store.
  3. SharedPreferences only take simple data, so we need to transform the object into a string, and we can achieve this by calling the json.encode() method over the book, transformed in json format, as shown in the following code snippet:
Future addToFavorites(Book book) async { 
SharedPreferences preferences = await SharedPreferences.getInstance();
String id = preferences.getString(book.id);
if (id != '') {
await preferences.setString(book.id, json.encode(book.toJson()));
}
}

Next, we'll write the method to delete an existing book from the favorites list. This takes the book to be deleted, and the current BuildContext. This is to reload the FavoriteScreen so that it gets updated. It's probably not the most elegant solution, as we could use a different approach to keep the state of the app, but it's good enough for this example.

The method to remove data from SharedPreferences is called remove(), and only takes the key of the value to be deleted.

  1. Add the following code to add the removeFromFavorites() method to the app:
Future removeFromFavorites(Book book, BuildContext context) async { 
SharedPreferences preferences = await
SharedPreferences.getInstance();
String id = preferences.getString(book.id);
if (id != '') {
await preferences.remove(book.id);
Navigator.push(context, MaterialPageRoute(builder:
(context)=> FavoriteScreen()));
}
}

The last method we need to add in the BooksHelper class is the getFavorites() async method. This will return the list of books that we'll retrieve from SharedPreferences.

  1. After creating an instance of SharedPreferences and creating the list that contains the books, use the getKeys() method to retrieve all the keys currently stored in SharedPreferences.
  2. If the set of keys is not empty, for each key, retrieve the value at the current position, using the get() method of the instance of SharedPreferences. This will be a String, so after converting it to a json, create a Book from the json, and add it to the list of books.
  3. Add the following code to complete the getFavorites() method:
Future<List<dynamic>> getFavorites() async { 
// returns the favorite books or an empty list
final SharedPreferences prefs = await
SharedPreferences.getInstance();
List<dynamic> favBooks = List<dynamic>();
Set allKeys = prefs.getKeys();
if (allKeys.isNotEmpty) {
for(int i = 0; i < allKeys.length; i++) {
String key = (allKeys.elementAt(i).toString());
String value = prefs.get(key);
dynamic json = jsonDecode(value);
Book book = Book(json['id'], json['title'],
json['authors'], json['description'],
json['publisher']);
favBooks.add(book);
}
}
return favBooks;
}

Now that the methods to read and write data to the favorites in our app are ready, we need to call them from the UI. Let's do that in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151