hydrated_bloc not persisting data
Asked Answered
C

1

5

I'm building a flutter app that uses BLoC pattern and using hydrated_bloc package to persist data.

The bloc itself is working fine, ie the event comes into the bloc and the bloc yields a state back to the ui.

The issue is that the bloc is not saving the json with the hydrated_bloc.

Here's the code for the bloc and event:

enum ConditionsEvent { snowyPressed, sunnyPressed, rainyPressed }

class ConditionsBloc extends HydratedBloc<ConditionsEvent, String> {
  ConditionsBloc() : super('unknown');

  @override
  Stream<String> mapEventToState(ConditionsEvent event) async* {
    switch (event) {
      case ConditionsEvent.snowyPressed:
        yield 'Snowy';
        break;
      case ConditionsEvent.sunnyPressed:
        yield 'Sunny';
        break;
      case ConditionsEvent.rainyPressed:
        yield 'Rainy';
        break;
    }
    throw UnimplementedError();
  }

  @override
  Map<String, dynamic> toJson(String state) {
    return <String, String>{'conditions': state};
  }

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

}

How can I get this to save the data in local storage using hydrated_bloc, so that when the user restarts app, the data is persisted? I think the problem is with toJson and fromJson.

Ceraceous answered 21/6, 2021 at 6:3 Comment(1)
toJson - conditions fromJson - valueMistrial
P
6

You made a mistake in the fromJSON while copy-pasta.
You need to use json['conditions'] instead of json['value'].

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

Provocative answered 21/6, 2021 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.