atomWithStorage<R, A> function

ReadOnlyAtom<R> atomWithStorage<R, A>(
  1. AtomWithStorageCreate<R, A> create, {
  2. required String key,
  3. required Atom<NucleusStorage> storage,
  4. required A fromJson(
    1. dynamic json
    ),
  5. required dynamic toJson(
    1. A a
    ),
})

Create an atom that can read and write to a NucleusStorage instance.

Can be used to wrap other state management tools with persistence.

Implementation

ReadOnlyAtom<R> atomWithStorage<R, A>(
  AtomWithStorageCreate<R, A> create, {
  required String key,
  required Atom<NucleusStorage> storage,
  required A Function(dynamic json) fromJson,
  required dynamic Function(A a) toJson,
}) =>
    atom((get) {
      final s = get(storage);

      void write(A value) => s.set(key, toJson(value));

      A? read() {
        final value = s.get(key);
        return value != null ? fromJson(value) : null;
      }

      return create(get, read, write);
    });