Code Monkey home page Code Monkey logo

hydrated_state_notifier's Introduction

Hydrated State Notifier

Pub hydrated_state_notifier License: MIT

Features

An extension to the state_notifier library which automatically persists and restores states using HydratedStorage. A hive implementation of HydratedStorage is hydrated_state_notifier_hive.

Usage

Setup HydratedStorage

Install

Add package to your project with

dart pub add hydrated_state_notifier hydrated_state_notifier_hive

Import package

Add below lines in your dart file

import 'package:hydrated_state_notifier/hydrated_state_notifier.dart';
import 'package:hydrated_state_notifier_hive/hydrated_state_notifier_hive.dart';

Initialize

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  /// Initialize the common storage by providing [HiveHydratedStorage]. 
  /// You can also provide your own implementation of [HydratedStorage].
  HydratedStorage.storage = await HiveHydratedStorage.build(
    storageDirectory: kIsWeb
        ? ''
        : await getTemporaryDirectory(),
  );

  runApp(App())
}

Create a HydratedStateNotifier

Does automatic state persistence for the [StateNotifier] class.

class CounterController extends HydratedStateNotifier<int> {
  CounterController() : super(0);

  void increment() => state = state + 1;

  @override
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  @override
  Map<String, int> toJson(int state) => { 'value': state };
}

Now the CounterController will automatically persist/restore their state. We can increment the counter value, hot restart, kill the app, etc... and the previous state will be retained.

It uses the same cache for the same type. Use the id parameter if you intend to have different cache for different intance of same type.

class CounterController extends HydratedStateNotifier<int> {
  CounterController(String id) : super(0, id: id);

  void increment() => state = state + 1;

  @override
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  @override
  Map<String, int> toJson(int state) => { 'value': state };
}

CounterController('first_counter');
CounterController('second_counter');

Create a HydratedStateController

A subclass of [HydratedStateNotifier] for simple scenarios.

final counterController = HydratedStateController(
    0,
    fromJson: (json) => json['count'] as int,
    toJson: (state) => {'count': state},
);

Now the counterController will automatically persist/restore their state. We can increment the counter value, hot restart, kill the app, etc... and the previous state will be retained.

It uses the same cache for the same type. Use the id parameter if you intend to have different cache for different intance of same type.

final counterController = HydratedStateController(
    0,
    fromJson: (json) => json['count'] as int,
    toJson: (state) => {'count': state},
    id: 'counter_1',
);
final counterController = HydratedStateController(
    0,
    fromJson: (json) => json['count'] as int,
    toJson: (state) => {'count': state},
    id: 'counter_2',
);

HydratedMixin

class CounterController extends StateNotifier<int> with HydratedMixin {
  CounterController() : super(0) {
    // Hydrate must be called if using HydratedMixin or implementing any 
    // [HydratedStateNotifier], or [HydratedStateController].
    hydrate();
  }

  void increment() => state = state + 1;

  @override
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  @override
  Map<String, int> toJson(int state) => { 'value': state };
  
  @override
  String get id => '';
  
  @override
  // Use a common storage or pass another
  HydratedStorage get storage => HydratedStorage.storage;
  
  @override
  // Will be used for writing migrations in a later version
  int get version => 1;
}

HydratedStorage

You can implement a custom Storage by simply implementing the HydratedStorage interface and initializing HydratedStateNotifier with the custom Storage.

// my_hydrated_storage.dart

class MyHydratedStorage implements HydratedStorage {
  @override
  Object? read(String key) {
    // TODO: implement read
  }

  @override
  Future<void> write(String key, Object? value) async {
    // TODO: implement write
  }

  @override
  Future<void> delete(String key) async {
    // TODO: implement delete
  }

  @override
  Future<void> clear() async {
    // TODO: implement clear
  }
}

Setting a common storage for all.

// main.dart

HydratedBloc.storage = MyHydratedStorage();
runApp(MyApp());

or providing storage through the parameters:

final counterController = HydratedStateController(
    0,
    fromJson: (json) => json['count'] as int,
    toJson: (state) => {'count': state},
    storage: MyHydratedStorage(),
);

// or

class CounterController extends HydratedStateNotifier<int> {
  CounterController(String id) : super(0, id: id, storage: MyHydratedStorage());

  void increment() => state = state + 1;

  @override
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  @override
  Map<String, int> toJson(int state) => { 'value': state };
}

Additional information

This is based on hydrated_bloc, and hydrated_notifier.

hydrated_state_notifier's People

Contributors

predatorx7 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.