0

我有这门课

@freezed
abstract class CartEntity with _$CartEntity {
  const factory CartEntity.empty(String status, String message) = _Empty;

  const factory CartEntity.notEmpty(int x) = _NotEmpty;

  factory CartEntity.fromJson(Map<String, dynamic> json) =>
      _$CartEntityFromJson(json);

}

而这个转换器

class CartEntityConverter
    implements JsonConverter<CartEntity, Map<String, dynamic>> {
  const CartEntityConverter();

  @override
  CartEntity fromJson(Map<String, dynamic> json) {
    //the problem here
    print(json);// null 

    return _Empty.fromJson(json);

  }

  @override
  Map<String, dynamic> toJson(CartEntity object) {
    return object.toJson();
  }
}

而这个包装类

@freezed
abstract class CartEntityWrapper with _$CartEntityWrapper {
  const factory CartEntityWrapper(@CartEntityConverter() CartEntity cartEntity) =
      CartEntityWrapperData;

  factory CartEntityWrapper.fromJson(Map<String, dynamic> json) =>
      _$CartEntityWrapperFromJson(json);
}

我叫

    final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
    print(cartEntity);

在 CartEntityConverter 中的 fromJson 方法总是接收空 json 那么我做错了什么?

4

2 回答 2

1

.fromJsonA您可以在主类中添加方法,而不是直接使用另一个转换器类。

它看起来像这样:

@freezed
abstract class CartEntity with _$CartEntity {
  const factory CartEntity.empty(String status, String message) = _Empty;

  const factory CartEntity.notEmpty(int x) = _NotEmpty;

factory CartEntity.fromJson(Map<String, dynamic> json) =>
      _$CartEntityFromJson(json);

  factory CartEntity.fromJsonA(Map<String, dynamic> json) {

if (/*condition for .empty constructor*/) {
      return _Empty.fromJson(json);
    } else if (/*condition for .notEmpty constructor*/) {
      return _NotEmpty.fromJson(json);
    } else {
      throw Exception('Could not determine the constructor for mapping from JSON');

    }
}

}
于 2021-04-13T21:01:09.053 回答
0

通过使用解决

    final cartEntity = CartEntityConverter().fromJson({'x':'y'});
    print(cartEntity);

代替

    final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
    print(cartEntity);

在这一点上缺少文档我尝试了随机的东西来使其工作

于 2020-12-20T17:08:08.063 回答