“This is the 28th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

background

We introduced a lightweight data persistence tripartite Get_Stroage use method, yesterday saw read and write storage source implementation, today we will look at other source implementation

listen

Listen is implemented by passing the callback method to list_Notifier, then calling the listener value change in getX and calling the callback method

VoidCallback listen(VoidCallback value) {
  return _concrete.subject.addListener(value);
}
Copy the code

listenKey

The same principle as above, except that the callback method filters the key and passes back the value corresponding to the key

VoidCallback listenKey(String key, ValueSetter callback) { final VoidCallback listen = () { if (changes.keys.first == key) { callback(changes[key]); }}; _keyListeners[callback] = listen; return _concrete.subject.addListener(listen); }Copy the code

ReadWriteValue

Now that we’re done with the main methods, how realistic is the chain method

0.val('count');
Copy the code

We create a ReadWriteValue object when we get the variable, and then we actually operate on the ReadWriteValue object

final count = 0.val('count');
Copy the code
class ReadWriteValue<T> { final String key; final T defaultValue; final StorageFactory? getBox; // final EncodeObject encoder; ReadWriteValue( this.key, this.defaultValue, [ this.getBox, // this.encoder, ]); GetStorage _getRealBox() => getBox? .call() ?? GetStorage(); T get val => _getRealBox().read(key) ?? defaultValue; set val(T newVal) => _getRealBox().write(key, newVal); }Copy the code

As you can see in ReadWriteValue there are get and set methods, which are the main ones we use

write

When you need to change the value, you can simply change val

count.val = 1;
Copy the code

The implementation is the same as if we call write directly, although we will check whether there is getBox first, generally we do not pass getBox, so we directly call GetStorage(), then call write

GetStorage _getRealBox() => getBox? .call() ?? GetStorage(); set val(T newVal) => _getRealBox().write(key, newVal);Copy the code

read

Count. Val = count. Val = count

T get val => _getRealBox().read(key) ?? defaultValue;
Copy the code

conclusion

Get_Stroage is the dart: HTML localStorage. If you have time, I’ll write another localStorage article later

I hope you can share some good three parties in the comments section, learn together and make progress together

As a student of Flutter, I hope you can give me more advice