hydrated_bloc 0.3.2 copy "hydrated_bloc: ^0.3.2" to clipboard
hydrated_bloc: ^0.3.2 copied to clipboard

outdated

An extension to the bloc state management library which automatically persists and restores bloc states.

logo
Build Status Code Coverage Pub Package MIT License


An extension to the bloc state management library which automatically persists and restores bloc states.

Usage #

1. Use HydratedBlocDelegate #

void main() async {
  BlocSupervisor.delegate = await HydratedBlocDelegate.build();
  runApp(App());
}

2. Extend HydratedBloc and override initialState, fromJson and toJson methods #

class CounterBloc extends HydratedBloc<CounterEvent, CounterState> {
  // You need to update state getter so it will get initialState
  // from storage when it is already populated/loaded and parsed 
  // without errors
  @override
  CounterState get initialState {
    return super.initialState ?? CounterState(0);
  }

  // This method is used to parse state object when retrieving its
  // saved JSON version from HydratedBloc internal storage.
  // Internally it is enclosed in try-catch block, so, to avoid
  // unexpected errors its better to thoroughly test method
  // somewhere else/enclose whole body and handle exceptions or
  // errors inside.
  @override
  CounterState fromJson(Map<String, dynamic> source) {
    return CounterState(source['value'] as int);
  }

  // Method which is used to convert bloc's state into JSON
  @override
  Map<String, int> toJson(CounterState state) {
    return {'value': state.value};
  }

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.decrement:
        yield CounterState(currentState.value - 1);
        break;
      case CounterEvent.increment:
        yield CounterState(currentState.value + 1);
        break;
    }
  }
}

enum CounterEvent { increment, decrement }

class CounterState {
  int value;

  CounterState(this.value);
}

Now our CounterBloc is a HydratedBloc and will automatically persist its state. We can increment the counter value, hot restart, kill the app, etc... and our CounterBloc will always retain its state.

838
likes
0
pub points
99%
popularity

Publisher

verified publisherbloclibrary.dev

An extension to the bloc state management library which automatically persists and restores bloc states.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

bloc, flutter, path_provider

More

Packages that depend on hydrated_bloc