Using a browser's local storage

Local storage (also called the Web Storage API) is widely supported in modern browsers. It enables the application's data to be persisted locally (on the client side) as a map-like structure: a dictionary of key-value string pairs, in fact using JSON strings to store and retrieve data. It provides our application with an offline mode of functioning when the server is not available to store the data in a database. Local storage does not expire, but every application can only access its own data up to a certain limit depending on the browser. In addition, of course, different browsers can't access each other's stores.

How to do it...

Look at the following example, the local_storage.dart file:

import 'dart:html';

Storage local = window.localStorage;

void main() {
  var job1 = new Job(1, "Web Developer", 6500, "Dart Unlimited") ;

Perform the following steps to use the browser's local storage:

  1. Write to a local storage with the key Job:1 using the following code:
      local["Job:${job1.id}"] = job1.toJson;
      ButtonElement bel = querySelector('#readls'),
      bel.onClick.listen(readShowData);
    }
  2. A click on the button checks to see whether the key Job:1 can be found in the local storage, and, if so, reads the data in. This is then shown in the data <div>:
     readShowData(Event e) {
       var key = 'Job:1';
       if(local.containsKey(key)) {
    // read data from local storage:
        String job = local[key];
        querySelector('#data').appendText(job);
       }
     }
    
    class Job {
      int id;
      String type;
      int salary;
      String company;
      Job(this.id, this.type, this.salary, this.company);
      String get toJson => '{ "type": "$type", "salary": "$salary", "company": "$company" } ';
    }

The following screenshot depicts how data is stored in and retrieved from local storage:

How to do it...

How it works...

You can store data with a certain key in the local storage from the Window class as follows using window.localStorage[key] = data; (both key and data are Strings).

You can retrieve it with var data = window.localStorage[key];.

In our code, we used the abbreviation Storage local = window.localStorage; because local is a map. You can check the existence of this piece of data in the local storage with containsKey(key); in Chrome (also in other browsers via Developer Tools). You can verify this by navigating to Extra | Tools | Resources | Local Storage (as shown in the previous screenshot) window.localStorage also has a length property; you can query whether it contains something with isEmpty, and you can loop through all stored values using the following code:

for(var key in window.localStorage.keys) {
String value = window.localStorage[key];
// more code
}

There's more...

Local storage can be disabled (by user action, or via an installed plugin or extension), so we must alert the user when this needs to be enabled; we can do this by catching the exception that occurs in this case:

try {
  window.localStorage[key] = data; 
} on Exception catch (ex) {
  window.alert("Data not stored: Local storage is disabled!");
}

Local storage is a simple key-value store and does have good cross-browser coverage. However, it can only store strings and is a blocking (synchronous) API; this means that it can temporarily pause your web page from responding while it is doing its job storing or reading large amounts of data such as images. Moreover, it has a space limit of 5 MB (this varies with browsers); you can't detect when you are nearing this limit and you can't ask for more space. When the limit is reached, an error occurs so that the user can be informed.

Note

These properties make local storage only useful as a temporary data storage tool; this means it is better than cookies, but not suited for a reliable, database kind of storage.

Web storage also has another way of storing data called sessionStorage used in the same way, but this limits the persistence of the data to only the current browser session. So, data is lost when the browser is closed or another application is started in the same browser window.

See also

  • For more information on the JSON format, refer to the Making toJSON and fromJSON methods recipe in Chapter 4, Object Orientation in your class
  • A better alternative to simple local storage is IndexedDB; see the Storing data locally in IndexedDB recipe in Chapter 9, Working with Databases
..................Content has been hidden....................

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