“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

background

Yesterday we introduced the use of a lightweight data persistence tripartite Get_Stroage method. Today we will see how to implement it

Initialize the

Yesterday we said that when you want to use Get_Stroage you have to init it, or if you want to create a new one you have to init it and pass it in a container, so now what do you do in init

static Future<bool> init([String container = 'GetStorage']) {
  WidgetsFlutterBinding.ensureInitialized();
  return GetStorage(container).initStorage;
}
Copy the code

WidgetsFlutterBinding. The ensureInitialized () is actually an initialization method of binding in runApp approach also have call, this time we do not do too much introduction first, then introduce the framework of time talk to you

If not, create a StorageImpl object and call init method, and determine whether the filename exists in the HTML localStorage. If yes, read it directly, save it directly Into a

factory GetStorage( [String container = 'GetStorage', String? path, Map<String, Dynamic >? InitialData]) {if (_sync.containskey (container)) {return _sync[container]! ; } else {// Create StorageImpl final Instance = getStorage. _internal(container, path, initialData); _sync[container] = instance; return instance; }}Copy the code
GetStorage._internal(String key, [String? path, Map<String, Dynamic >? InitialData]) {// just create a StorageImpl,init method below _concrete = StorageImpl(key, path); _initialData = initialData; initStorage = Future<bool>(() async { await _init(); return true; }); } Future<void> init([Map<String, dynamic>? initialData]) async { subject.value = initialData ?? <String, dynamic>{}; If (await _exists()) {await _readFromStorage(); } else { await _writeToStorage(subject.value!) ; } return; }Copy the code

At this point, the initialization method is complete, as is creating a new Storage

Add and delete

To use it, you need to get a singleton and then pass it

read

Read from ValueStorage, which inherits the ListNotifier in Get, which we’ll talk about later

write

Valuestorage. value map is used to write data to memory first, and then to disk. There are two key points here. First, a Microtask appears when disk is refreshed Speak), and then the second is used here to scheduleMicrotask, scheduleMicrotask priority is higher, higher than the Future

class Microtask { int _version = 0; int _microtask = 0; void exec(Function callback) { if (_microtask == _version) { _microtask++; scheduleMicrotask(() { _version++; _microtask = _version; callback(); }); }}}Copy the code

remove

The ValueStorageremove method is first called, followed by _tryFlush() to flush the disk, as with write

conclusion

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