Having stored our data in local storage, it is just as easy to read this data from local storage. Here is a simple screen that takes a bank account number as input, and reads its data when the number field is filled in:
We clean up our code making main()
shorter by calling methods:
void main() {
bind_elements();
attach_event_handlers();
}
bind_elements() {
owner = querySelector('#owner'),
balance = querySelector('#balance'),
number = querySelector('#number'),
btn_other = querySelector('#btn_other'),
error = querySelector('#error'),
}
attach_event_handlers() {
number.onInput.listen(readData);
btn_other.onClick.listen(clearData);
}
Apply this refactoring from now on when coding a form. When the number is filled in, its Input event listener is triggered:
number.onInput.listen(readData);
In the readData
handler, the value is read from the local storage where the key contains the bank account number (line (2)
). But first, we will check whether our input sits in the local storage; if not, an error label is shown. The field gets focus and we leave the method with return (line (1)
and following):
readData(Event e) { // show data: var key = 'Bankaccount:${number.value}'; if (!window.localStorage.containsKey(key)) { (1) error.innerHtml = "Unknown bank account!"; owner.innerHtml = "----------"; balance.innerHtml = "0.0"; number.focus(); return; } error.innerHtml = ""; // read data from local storage: String acc_json = window.localStorage[key]; (2) bac = new BankAccount.fromJson(JSON.decode(acc_json)); (3) // show owner and balance: owner.innerHtml = "<b>${bac.owner.name}</b>"; (4) balance.innerHtml = "<b>${bac.balance.toStringAsFixed(2)}</b>"; }
The bank account object bac
is now created in line (3)
, and the owner
and balance
labels can then be filled in line (4)
. Let's examine this in some detail. The resulting string acc_json
has the structure of a map, and the JSON.decode
method of the convert package transforms this string into a map. We will enhance our model classes with functionality to convert this map into an object. The best way to do this is with a named constructor (called appropriately fromJson
) that takes this map and makes a new object from it. So in the person
class, we add the following named constructor:
Person.fromJson(Map json) { this.name = json["name"]; this.address = json["address"]; this.email = json["email"]; this.gender = json["gender"]; this.date_birth = DateTime.parse(json["birthdate"]); }
This is used by the fromJson
constructor in the BankAccount
class:
BankAccount.fromJson(Map json): date_created = DateTime.parse(json["creation_date"]) { this.number = json["number"]; this.owner = new Person.fromJson(json["owner"]); this.balance = json["balance"]; this.pin_code = json["pin_code"]; this.date_modified = DateTime.parse(json["modified_date"]); }
18.222.182.66