hydrated_bloc 0.2.0 hydrated_bloc: ^0.2.0 copied to clipboard
An extension to the bloc state management library which automatically persists and restores bloc states.
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
#
enum CounterEvent { increment, decrement }
class CounterState {
int value;
CounterState(this.value);
}
class CounterBloc extends HydratedBloc<CounterEvent, CounterState> {
@override
CounterState get initialState {
return super.initialState ?? CounterState(0);
}
@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;
}
}
@override
CounterState fromJson(Map<String, dynamic> source) {
return CounterState(source['value'] as int);
}
@override
Map<String, int> toJson(CounterState state) {
return {'value': state.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.