【问题标题】:hydrated_bloc not persisting datahydrad_bloc 不持久化数据
【发布时间】:2021-09-04 20:04:06
【问题描述】:

我正在构建一个使用 BLoC 模式并使用 hydrad_bloc 包来持久化数据的颤振应用程序。

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

问题是 bloc 没有使用 hydrad_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;

}

如何使用 hydrad_bloc 将数据保存在本地存储中,以便在用户重新启动应用程序时保留数据?我认为问题出在toJson 和fromJson。

【问题讨论】:

  • toJson - 来自Json 的条件 - 值
  • @SimonSot 非常感谢您发现我的错误!现在完美运行

标签: flutter dart bloc


【解决方案1】:

您在复制意大利面时在 fromJSON 中犯了一个错误。
您需要使用 json['conditions'] 而不是 json['value']。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多