Hydrod_bloc 不持久保存数据

Jas*_*oyd 5 dart flutter bloc

我正在构建一个使用 BLoC 模式并使用 Hydrated_bloc 包来保存数据的 flutter 应用程序。

块本身工作正常,即事件进入块并且块将状态返回给 ui。

问题是 bloc 没有使用 Hydrated_bloc 保存 json。

这是块和事件的代码:

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;

}

Run Code Online (Sandbox Code Playgroud)

如何使用 Hydrated_bloc 将数据保存在本地存储中,以便当用户重新启动应用程序时,数据得以保留?我认为问题在于toJsonfromJson

Kan*_*shi 6

您在复制 Pasta 时在 fromJSON 中犯了一个错误。
您需要使用 json['条件'] 而不是 json['']。

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

Run Code Online (Sandbox Code Playgroud)