json = 自定义 JsonConverter 中的 fromJSON 方法中的 null“冻结 class 具有多个构造函数”

json = null in fromJSON method in custom JsonConverter " freezed class with multiple constructors "

我有这个class

@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();
  }
}

还有这个包装器 class

@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);

FromJson 方法,在 CartEntityConverter 中总是收到 null json 所以我做错了什么?

使用

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

而不是

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

目前缺少文档我尝试了一些随机的东西来让它工作

您可以直接在主 class.

中添加 .fromJsonA 方法,而不是直接使用另一个转换器 class

看起来像这样:

@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');

    }
}

}