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

outdated

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

Hydrated Bloc #

Pub License: MIT


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

Usage #

1. Extend HydratedBlocDelegate #

class MyHydratedBlocDelegate extends HydratedBlocDelegate {
  MyHydratedBlocDelegate(HydratedBlocSharedPreferences prefs) : super(prefs);

  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print('${bloc.runtimeType} $event');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('${bloc.runtimeType} $transition');
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    print('${bloc.runtimeType} $error');
  }
}

2. Use HydratedBlocDelegate #

void main() async {
  final prefs = await HydratedBlocSharedPreferences.getInstance();
  BlocSupervisor.delegate = MyHydratedBlocDelegate(prefs);
  runApp(App());
}

3. 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
  fromJson(String source) {
    try {
      final dynamic j = json.decode(source);
      return CounterState(j['value']);
    } catch (_) {
      return null;
    }
  }

  @override
  String toJson(CounterState state) {
    Map<String, int> j = {'value': state.value};
    return json.encode(j);
  }
}

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, meta, shared_preferences

More

Packages that depend on hydrated_bloc